Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Object reference not set to an instance of an object help

Discussion in '2D' started by JackAshwell, Nov 9, 2019 at 5:24 PM.

  1. JackAshwell

    JackAshwell

    Joined:
    Oct 21, 2019
    Posts:
    16
    So this is my current code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class Score : MonoBehaviour
    7. {
    8.     Text score;
    9.     public static int coinAmmount = 1;
    10.  
    11.     void Start() {
    12.         score = GetComponent<Text> ();
    13.     }
    14.    
    15.     void Update()
    16.     {
    17.         score.text = "Score: " + coinAmmount.ToString();
    18.     }
    19. }
    And it works fine, the counter is incremented on screen when i get a coin. But it still gives me this error:

    NullReferenceException: Object reference not set to an instance of an object
    Score.Update () (at Assets/Scripts/Score.cs:17)


    Can anyone explain why?

    Thanks!
     
  2. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    623
    Code (CSharp):
    1. public Text score; // drag yout Text UI inside the inspector
    Now you don't need to get the component Text on Start anymore and your code should work now.

    Edit:

    To explain why you're getting that error message, You're grabbing the UI Text not the Text.text so when you try to use Text.text it is sending you a null reference because it is empty. I'm not 100% sure but using your method you could probably still accomplish .enabled = true/false;
    But I think it's just better to drag it in the field and not worry about grabbing an object on load.
     
    Last edited: Nov 9, 2019 at 11:23 PM
    vakabaka likes this.
  3. JackAshwell

    JackAshwell

    Joined:
    Oct 21, 2019
    Posts:
    16
    Yea sorry, the error still shows up.
     
  4. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,134
    with public Text score; you can see the field in the inspector. If the game is paused because of error, switch in the scene (by paused game) tab and check if this field is empty (can it be that you have deleted the ui-text somewhere in the game)?
     
    Last edited: Nov 10, 2019 at 2:43 PM
    MisterSkitz likes this.
  5. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    623
    Same error message? Did you remove :
    Code (CSharp):
    1. void Start()
    2. {
    3. score = GetComponent<Text>();
    4. }
    You wont need this anymore because you are dragging the text into the score field inside of the inspector.