In Unity when i return a list I am returnning a copy or the original
- User
In Unity when i return a list I am returnning a copy or the original
- Assistant
In Unity, which is built on top of the .NET framework, when you return a
List<T>from a function, you are actually returning a reference to the original list, not a copy of it. Lists in C#, and by extension Unity, are reference types. This means that when you pass a list to a function or return it from a function, you are passing a reference that points to the same memory location where the list is stored.Here is a small example to illustrate this:
using System.Collections.Generic; using UnityEngine; public class ListExample : MonoBehaviour { void Start() { List<int> originalList = new List<int> { 1, 2, 3 }; List<int> returnedList = GetList(originalList); // Let's modify the returned list returnedList.Add(4); // Now let's see the contents of both lists Debug.Log("Original List:"); foreach (int i in originalList) { Debug.Log(i); // This will print 1, 2, 3, 4 } Debug.Log("Returned List:"); foreach (int i in returnedList) { Debug.Log(i); // This will also print 1, 2, 3, 4 } } List<int> GetList(List<int> list) { // Simply return the reference we received return list; } }