- Home /
List Of GameObjects , Deleting these Objects !
i add objects in Run Time to a -> List();
fruits.Add((GameObject)Instantiate(fruit,transform.position, Quaternion.identity));
OnTriggerEnter() i destroy the Collider GameObject, which is a GameObject inside that list
void OnTriggerEnter(Collider col)
{
Destroy(col.gameObject);
}
Now my Question is, once i destroy it, will it also be removed from the List, Or i have to manually remove it from the List by accessing it...
Answer by syclamoth · Nov 13, 2011 at 03:06 PM
The list will remain the same length- the destroyed gameObject will be replaced with a null reference. So, neither? I would recommend removing it manually before it gets destroyed, though- that would reduce confusion.
So if i say this fruits.Remove(col.gameObject);
will it be destroyed :D ?
or i have to do this
fruits.Remove(col.gameObject); Destroy(col.gameObject);
??
Thanks for helping.
You have to both remove it from the list, and also destroy it. They are two separate operations which do not directly affect one another, but you can only do them in one order (otherwise the object won't exist, so you won't be able to remove it from the list).
Answer by NDLeo · Nov 01, 2014 at 09:19 PM
Its easier way to do it. Destroy all object in list and then use Delegate to clear all null object in list
SomeList.RemoveAll (delegate (GameObject o) { return o == null; });
Well, actually it's not easier since it's way longer than SomeList.Remove(item);
. However if you can Destroy multiple objects at once, it would be more efficient since RemoveAll iterates through the list only once.
Here's a shorter version:
SomeList.RemoveAll((o)=>o == null);
Read about lambdas here
Your answer
Follow this Question
Related Questions
Gather all GameObjects with a certain name in a Scene and Apply them to a list? 3 Answers
Why does the script don't apply to the other duplicated player 0 Answers
How to find all similar elements in a list? 1 Answer
How do i activate a function attached to a listed GameObject from the perspective of itself? 1 Answer
In a group of gameobjects, how to have only one object active at a time while disabling the others? 2 Answers