Problem with Destroy function with instantiated Prefabs

Hi!

I have very peculiar problem. In my game, I instantiate a lot of 4 different kinds of objects (from prefabs). The objects have Kinematic Rigidbody Trigger Colliders attached to them.

I use OnTriggerEnter2D() to handle the logic when two of these colliders collide with each other. In the function I just check that if the other collider is with marked with tag “Moving”, and if it is, I Destroy it.

void OnTriggerEnter2D(Collider2D other) {
           
        if (other.gameObject.tag == "Moving")
        {
            Destroy(other.gameObject);

Then, I check if the other Gameobject get actually destroyed;

            if(other.gameObject == null)
            {
                Debug.Log("Object " + other.gameObject.name + " got destroyed");
            }

Then I call the moveThisBall which handles the moving of the ball which the destroyed object touched.

moveThisBall();
        }

The problem is that everything seems to work fine EXCEPT with one problematic type of object which was instantiated. All other objects work fine. I have checked, double-checked and triple-checked that everything in the original Prefab is just the same way than in other Prefabs that gets instantiated and they are exactly the same (except graphical presentation).

The source of the problem is that when this problematic object enters to the trigger collider of other object, for some reason it doesn’t Destroy the problematic gameobject soon enough. Instead, the code gets so far up in the process that this other gameobject gets tagged with “Moving” tag as well and when the program finally starts to Destroy the gameobject, it destroys both objects. Which is not something that I want.

So my problem is two-fold;

  1. I don’t understand why with this problematic object, the code gets fired in the other object so long that the other gets tagged with “moving”. This doesn’t happen with other gameobjects.
  2. I don’t know how to circumvent this problem, i.e. how to make the program Destroy the problematic gameobject before the other gameobject gets tagged with “Moving” tag.

Any help would be highly appreciated!

  • Jukka

In general you should design your code based on the fact that Destroy() doesn’t happen immediately. The documentation of Destroy() says the actual destruction is guaranteed to happen before the next Update cycle, nothing else. Checking ‘object == null’ right after the Destroy() call can definitely give you misleading information.

I guess the difference between objects could be explained by script execution order, but as said, youd be better off flagging your destroyed objects in some way that prevents them from doing anything you don’t want them to do.