Stop onDestroy on Scene Load.Unity 2d

Viewed 41

So I have a script that adds money when enemy dies (onDestroy). But when the scene changes that also destroys the enemies and adds money. How I can make it only add money when enemy is destroyed by health=0 and not on scene change? Code:

void onDestroy()
{
AddCoins(Coins);
}
3 Answers

I can see two main ways to do this :

  • If it's possible, call the AddCoins Method in the code that calls Destroy() when health =0 instead of in OnDestroy(). Something like :
    if(health == 0){
       AddCoins(coins);
       Destroy(gameObject);
    }

and no OnDestroy method.

  • Otherwise, you could set a variable to true just before loading a new scene, and in OnDestroy() check if this variable is false, and only then adding coins.

If it's compatible with your game, I would recommend for the first solution, much cleaner in my opinion.

You can use scene.isLoaded to only check the times when the scene is loaded and is not changing.

void OnDestroy()
{
    if(gameObject.scene.isLoaded)
    {
        AddCoins(Coins);     
    }
}

I would make it so that the AddCoin() method gets called not on destroy but instead have a check either in the update loop or ideally in your enemy damage function so it gets called only when health changes.

void Update()
{
   if(health == 0)
   {
      AddCoins(Coins)
      Destroy(gameobject)
   }
}

if you want to use your existing code structure and still have it be called onDestory you could add another check

void onDestroy()
{
   if(health == 0)
   {
     AddCoins(Coins);
   }

}
Related