A List that won't clear for no obvious reason

 public void ChangeMat(float M)
    {
           Current.Clear(); // This One Doesn't Clear
        if (Spawner == Cactus)
            Spawner = Tree;
        foreach (GameObject C in Cacti)
            Destroy(C);
        Cacti.Clear(); // This one Clears.
        Current.Clear(); /// won't clear here either.
        // So Since "Cacti" Clears to count 0 after destroying the objects;
       Current = Cacti; // Still doesn't clear.
    }

objects that are colliding with player sphere are added to Current list; when this above method is called; All objects on the map(cacti) are destroyed, and all current objects known in player sphere turn into missing game object, and It wont clear it as It cant seem to clear a missing game object list that is being supplied by OnTriggerStay(); even when no collisions are providing it with data… So. IDK>

I disable the collider feeding OnTriggerStay; so that our list “Current” is not being supplied with entries; and then try to clear it to count 0. The answer is no.

It either wants the code posted; so it’ll magically work again, or. Its broken!? Disabling player colliders before method is called, or during the method; won’t work either.

What makes you think it’s not clearing? Have you tried logging the size of the list before and after clearing?

Debug.Log($"Items in Current: {Current.Count}");
1 Like

List.Clear() is a pretty well tested method. The issue is highly likely with your understanding of what is happening rather than the list not actually clearing. Add the Debug.Log line @PraetorBlue suggested before and after attempting to clear the list.

My guess would be that you aren’t clearing the variable that you think you’re clearing. Some ways this might happen include:

  • Your scene contains two instances of this script, and you’re clearing the variable on the wrong instance
  • You have two variables with the same name at different scopes (e.g. one declared in the class, another declared in the function), so one shadows the other
  • At some point you have made a copy when you thought you made a reference

Of course, it also could be that the list is cleared, but immediately repopulated by some other code somewhere.

1 Like