Home > Software design >  NullReferenceException: OnDestroy() function error
NullReferenceException: OnDestroy() function error

Time:05-04

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
    }

}

Game manager script

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

public class gamemanager : MonoBehaviour
{ 
    string ScoreText_string;
    
    public TMPro.TextMeshProUGUI ScoreText;
    int score;
    
    public void NextLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex   1);
    }
    public void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
    public void plusScore(int Score)
    {
        score  = Score;
    }
    void Update() 
    {   ScoreText_string = score.ToString();
        ScoreText.text = ScoreText_string;

    }

        
    
}

editor version 2021.3

CodePudding user response:

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.

CodePudding user response:

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

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

CodePudding user response:

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