Trying to create a reaction to the way in that an object is destroyed, but it's behaving oddly.

I'll try to make this short.

I have an object that, when it leaves the screen, it is destroyed (since it will never come back anyways, and should no longer be effectual).

However, I want to make it so that when this object is destroyed on-screen, it behaves normally and spawns a secondary effect. For simplicity, I won't bother explaining what my language means since it's very specific to the game, just know that I have a projectile that can be destroyed from leaving the screen, or destroyed from impacting an enemy. It should spawn a secondary projectile when it dies from hitting an enemy, but NOT from leaving the screen.

However, when I put the check in place, it always thinks it has left the screen.

    void OnBecameInvisible()
    {
        LeftTheScreen = true;
        GameObject.Destroy(gameObject);
    }

    void OnDestroy()
    {
        if ((GenerateNukelets) && (!LeftTheScreen))
        {
            Instantiate(NukeletPrefab, transform.position, transform.rotation);
        }    
    }

It never lets my LeftTheScreen boolean stay at its default value. Somehow it always trips "OnBecameInvisible" even when it hasn't actually left the screen and was destroyed on-screen. Very confused here.

If I remove the check and the boolean, it generates these secondary effects properly, but it also does it when the item leaves the screen and is destroyed, which I don't want.

1 Answer

1

At a guess: destroying an object implies that, at some point in the process, it will stop being visible to any cameras. So, OnBecomeInvisible is firing at that point.

Spawning these effects in OnDestroy seems a bit troublesome, because I think there are a bunch of other times that it might fire that you maybe don't expect - for example, when exiting/unloading the scene. Maybe you could rewrite it as an Explode() method, replace your existing calls to Destroy() with SendMessage("Explode"), and have the object destroy itself when it's finished spawning things?

That should ensure that effects only ever might be spawned if you deliberately offer them the opportunity, rather than happening because you're cleaning them up for some other reason.