Search Unity

error thrown by unity about null reference exception

Discussion in 'Scripting' started by danmct1995, May 6, 2020.

  1. danmct1995

    danmct1995

    Joined:
    Apr 21, 2020
    Posts:
    70
    The error states that my object reference is not set to the instance of an object. The error is thrown in this section of my code.

    Code (CSharp):
    1.     public void MainMenuKey()
    2.     {
    3.         if (Input.GetKey(KeyCode.Return))
    4.         {
    5.             SceneManager.LoadScene(0);
    6.         }
    7.         else if (Input.GetKey(KeyCode.Backspace))
    8.         {
    9.             SceneManager.LoadScene(0);
    10.         }
    11. // LINE THROWING ERROR
    12.         FindObjectOfType<GameSession>().resetScore();
    13.     }
    The method is held in another script and is very simple:

    Code (CSharp):
    1.     public void resetScore()
    2.     {
    3.         Destroy(gameObject);
    4.     }
    I don't understand why its throwing this error code. Should I just write to destroy the game object at the end of my other code instead of calling the method from the other script?
     
  2. matkoniecz

    matkoniecz

    Joined:
    Feb 23, 2020
    Posts:
    170
  3. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    It would help if you showed the actual error message, but my guess would be that FindObjectOfType<GameSession>() returns null, thus null.resetScore() throws the exception. Does an object with a script of type GameSession attached exist in your scene hierarchy?
     
    PraetorBlue likes this.
  4. danmct1995

    danmct1995

    Joined:
    Apr 21, 2020
    Posts:
    70
    The exact error is:

    NullReferenceException: Object reference not set to an instance of an object
    PlayAgain.MainMenuKey () (at Assets/Scripts/PlayAgain.cs:30)
    PlayAgain.Update () (at Assets/Scripts/PlayAgain.cs:17)
     
  5. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    So, .. did you check what i wrote?
     
    Vryken and matkoniecz like this.