Wanted a game object to remove itself from an array once it's destroyed, but it gives null errors

This is the script that I have used:

public class Perishable : MonoBehaviour {
    public void OnDestroy() {
        if (this.gameObject != null) {
            Debug.Log("Removing traces of this game object from unit manager. Object: " + this.gameObject.name);
            UnitManager.Instance.PlayerUnits.Remove(this.gameObject);
            UnitManager.Instance.AllUnits.Remove(this.gameObject);
            Debug.Log("Current unit count: " + UnitManager.Instance.PlayerUnits.Count.ToString());
        }
    }
}

Whenever this game object with the script is destroyed, it would give NullReferenceException errors, stating that “this.gameObject” is null.

How do you fix this?

When I use this script…
Click for code

    void Start()
    {
        Destroy(gameObject);
    }

    public void OnDestroy() //you dont need "public" on this
    {
        if(this.gameObject != null)
        {
            Debug.Log("Removing traces of this game object from unit manager. Object: " + this.gameObject.name);
        }
    }

…everything works fine.

Where does the NullReferenceException point to? What is this code doing?

UnitManager.Instance.PlayerUnits.Remove(this.gameObject);
UnitManager.Instance.AllUnits.Remove(this.gameObject);

Are any of these destroying the gameobject?

Also, I dont think you need to do “this.gameObject”, “gameObject” should be fine.

The word, “this”, is a holdover from doing Java programming. It’s just a style I am very used to.

The UnitManager is just a List<> array. Nothing more. They do not destroy object. The game object is destroyed by Network.Destroy(). I have no idea how to describe it.

I am getting errors just by calling Network.Instantiate() on a prefab and Network.Destroy() the same prefab.

But where do the errors point to? What line?

Oh, I didn’t realize errors are not highlighted in the Code snippet.

The errors are pointing at:

UnitManager.Instance.PlayerUnits.Remove(this.gameObject);
UnitManager.Instance.AllUnits.Remove(this.gameObject);