NullReferenceException: OnDestroy() function error

Viewed 75

In my game I have coins, in my coin script I have an OnDestroy() function but I get this error "NullReferenceException: Object reference not set to an instance of an object coinscript.OnDestroy () (at Assets/Scrips/coinscript.cs:9)"

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class coinscript : MonoBehaviour
{   public gamemanager GameManager;
    void OnDestroy() 
    {
       GameManager.plusScore(10);// FindObjectOfType<gamemanager>().pluseScore(10); gets the same error
    }

}

fixed it thanks to help from KiynL

using System.Collections.Generic;
using UnityEngine;

public class coinscript : MonoBehaviour
{   public gamemanager GameManager;
    bool destroyed = false;
    void OnDestroy() 
    {
       if (destroyed = false) 
       {
           GameManager.plusScore(10);
           destroyed = true;
       }
    }

}
3 Answers

You need to go into the properties of whatever object you attached that script to, and assign Game Manager an object that has a gamemanager script attached to it.

This is because the object may be destroyed multiple times in one frame. Fix it.

void OnDestroy() 
{
    if (gameObject) GameManager.plusScore(10);
}

As ted said its probably because you haven't set GameManager from inspector. you need to drag a gameObject that has gamemanager component on it.

but I recommand making plusScore function static and calling it without an object, if you make it statis you also have to make varible that stores score static as well, some thing like this:

public class gamemanager : MonoBehaviour
{
    static int Score = 0;
    public static void plusScore(int score)
    {
        Score += score;
    }
}

then calling it like this:

gamemanager.plusScore(10);
Related