Issue with GameObject has been destroyed but it is not destroyed

Hi there everyone. I am having a little issue with with a GameObject that is active in the scene but when the player has a collision on the GameObject, the GameObject will not disappear.


My Script is written to destroy the GameObject when a collision has occurred, however, the GameObject is not destroying.


I have included a photo of Unity’s messages to let you know what is happening. You will see that the GameObject is throwing an error as it say “GameObject has been destroyed but you are still trying to call it.” What is interesting is that after the fourth time of allowing the player to collide with the same GameObject as it respons, the player performs an upgrade function that is in the code attached to the player GameObject.


My question is: How do I go about and fix this issue as the GameObjects are working properly but still calling for an error as the GameObject has been destroyed when it is still currently in the scene.


Here is my code:


public enum BonusType1 
{
    levelup
}

public enum BonusType2
{
    levelup
}

public class Bonus : MonoBehaviour {

    public BonusType1 bonusType1;
    public BonusType2 bonusType2;

private void OnTriggerEnter2D(Collider2D collision) 
    {
        if (collision.tag == "Player") 
        {
            switch (bonusType1)
            {
                //if 'weapon power' not more than 'max weapon power', increase weapon power level
                case BonusType1.levelup:
                    SoundManager.instance.PlaySound("powerUp");
                    if (PlayerShooting.instance.weaponPower1 < PlayerShooting.instance.maxweaponPower)
                    {
                        PlayerShooting.instance.weaponPower1++;
                        PlayerShooting.instance.guns1.PlayerRay.GetComponent<PlayerRay>().UpdateVfx();
                    }
                    break;
            }
            Destroy(gameObject);
        }

        if (collision.tag == "Player")
        {
            switch (bonusType2)
            {
                //if 'weapon power' not more than 'max weapon power', increase weapon power level
                case BonusType2.levelup:
                    SoundManager.instance.PlaySound("powerUp");
                    if (PlayerShooting.instance.weaponPower2 < PlayerShooting.instance.maxweaponPower)
                    {
                        PlayerShooting.instance.weaponPower2++;
                        PlayerShooting.instance.guns2.PlayerRay.GetComponent<PlayerRay>().UpdateVfx();
                    }
                    break;
            }
            Destroy(gameObject);
        }
    }
}

Here is my pictures:



After a gameObject is destroyed, it will be set to null. When you try to access a gameObject that has been destroyed, it will throw an error and produce unpredictable results.

Change:

if (collision.tag == “Player”)

to:

if (collision.tag == “Player” && gameObject != null)