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

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 = “test”;

But it does exist:

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!

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.