Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

c sharp - NullReferenceException: Object reference not set to an instance of an object

Discussion in 'Scripting' started by zigglr, Jul 4, 2018.

  1. zigglr

    zigglr

    Joined:
    Sep 28, 2015
    Posts:
    82
    Unity is giving an error:

    NullReferenceException: Object reference not set to an instance of an object
    questions.Start () (at Assets/scripts/questions.cs:22)

    Line 22 is this:

    GameObject.Find("answer1").GetComponent<Text>().text = "test";

    But it does exist:

     
  2. TimmyTheTerrible

    TimmyTheTerrible

    Joined:
    Feb 18, 2017
    Posts:
    186
    The problem is your using get component text on answer1. It does not have a text component.

    It's child however, named Text, does have a text component. Use GetComponentInChildren. Also, I would never ever use something like item.GetComponent().Function(). The reason being is you always want to make sure that GetComponent () actually found a component. ALWAYS test for null first!
     
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,186
    As mentioned, it's null cause it doesn't have a Text component, but note that GameObject.Find is not the best thing to use anyways. You should use a direct reference whenever possible instead of trying to find objects as GameObject.Find is slow.