- Home /
Removing object from a list also removes it from a different list? help!
Right, my brain has melted and google has failed me. The following script is just a test, on playing in populates list1 with all transforms inside a trigger tagged "tagged". Pressing 'K' then fills the list2 with all transforms in list1 Pressing 'O' chooses the first transform in list2 pressing 'L' removes the transform from list2
Now, this works almost as required ... but it also removes the transform from list1 even though i specifically asked it to only removed from list2. Im obviously missing something here but after hours and hours i can't figure it out, please help!
public Transform transform1;
public List<Transform> list1;
public List<Transform> list2;
void Start ()
{
list1 = new List<Transform> ();
list2 = new List<Transform>();
}
void OnTriggerEnter (Collider other)
{
if (other.tag == "tagged")
{
list1.Add(other.transform.root);
}
}
void OnTriggerExit (Collider other)
{
if (other.tag == "tagged")
{
list1.Remove(other.transform.root);
}
}
void Update()
{
if (Input.GetKeyDown ("k"))
list2 = list1;
if(Input.GetKeyDown("o"))
transform1 = list2 [0];
if (Input.GetKeyDown ("l"))
{
list2.Remove(transform1);
}
}
}
Answer by robertbu · May 11, 2014 at 03:11 PM
A list is a reference or a pointer to a pool of memory. When you do this:
list2 = list1;
...you create two variables pointing to the same pool of memory. If you want to copy the array, you have to do something like:
list2 = new List<Transform>(list1);
Now 'list2' now points to its own pool of memory and has a copy of all the entries in 'list1'. But there is still something to pay attention to here. Say you did this:
list2[2].position.x = 3.5f;
If the transform pointed to by 'list2[2]' exists in both lists, then the 'position.x' changes in both lists. That is because the Transforms that you put into the two lists are also by reference, and entries in the list that point to the same Transform will both have their data changed.
For more information Google ".NET shallow deep copy." Here is one hit:
Answer by Deign · May 11, 2014 at 03:09 PM
It is because you're setting list2 = list1. This does not make a copy of the list, it simply makes a reference to the first list. Try this instead:
list2 = new List<Transform>(list1);
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
How to remove project from the Project Wizard 6 Answers
List That Won't Remove The Last Two Elements 3 Answers