Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Bug Object reference not set to an instance of an object error

Discussion in 'Scripting' started by AFatBreakfastCat, Sep 23, 2023.

  1. AFatBreakfastCat

    AFatBreakfastCat

    Joined:
    Jul 30, 2022
    Posts:
    3
    I am currently working on a clicker game and I came across this error.
    The error says NullReferenceException: Object reference not set to an instance of an object. The error is on line 15.

    Line 15: RobotDisplay.GetComponent<Text>().text = "Robots: " + InternalRobot;
    Here is my code:

    Any ideas on what is causing this error?
     

    Attached Files:

  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,860
    An object reference is null.

    On line 15, there are two object references that you're assuming are not null.

    Either you did not fill in the RobotDisplay field in the Inspector, or the RobotDisplay object you provided does not have a Text component on it.
     
  3. AFatBreakfastCat

    AFatBreakfastCat

    Joined:
    Jul 30, 2022
    Posts:
    3
    I checked and it looked like I filled in the RobotDisplay in the inspector and it has a text component in it. But, I just realized that my text is a TextMeshPro. Is that the reason that it is not working? Do I have to declare something?
     
  4. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,860
    Text is not TextMeshPro. Computers don't guess and second-guess what you mean, they do what you say.

    If you want to set the text of a TextMeshPro component, you should say so in your code with
    GetComponent<TextMeshPro>()
    . It will probably throw a new error when you make this change, until you add
    using TMP;
    near the top of your script.
     
    AFatBreakfastCat likes this.
  5. AFatBreakfastCat

    AFatBreakfastCat

    Joined:
    Jul 30, 2022
    Posts:
    3
    Ah, thats why. Still getting the error though after changing it. Is there anything else I have to change?