2
votes

Im having an error during runtime with my image and text. I have both objects created in my hierarchy named correctly but apparently my script cant find them. Why isn't what i have written not sufficient? All i get in the error is Object reference not set to an instance of an object, but i don't understand why i need to create an instance of this object when i have one in my hierarchy. I'm still relatively new to both unity and c# and couldn't find any real explanatory answer by searching and the unity tutorials weren't very helpful since I'm sure its just a basic question about c#

private Text serverInfoText;
private GameObject serverInfoImage;

void Awake()
{
    serverInfoImage = GameObject.Find ("ServerInfoImage");
    serverInfoImage.SetActive (false);
    serverInfoText = GameObject.Find("ServerInfoText").GetComponent<Text>();
}
1
have attached this scrip to a gameobject in the scene? if not, do it! - Dinal24

1 Answers

5
votes

Impossible to say without looking at your scene.

Things to try:

  • GameObject.Find only works on active game objects. Make sure the game objects are not greyed out in your scene view.
  • Double check the name strings are correct and use Debug.Log to sanity check.
  • You don't mention which line the actual exception occurs. In your above code, it's possible to throw an exception in two locations: on SetActive() if serverInfoImage is null, or on GetComponent<Text>() if the ServerInfoText object is not found. Read the actual exception message you get and make sure you are looking at the correct line/object.
  • Since your objects are already created in your scene, there's no advantage to using GameObject.Find to get references to the objects. It would be more efficient to directly set the references to the objects via the inspector. This option has the added benefit of working with disabled GameObjects. Either make your two member variables private, or use the SerializeField attribute to make the properties visible in the inspector.