2

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! Commented Feb 26, 2015 at 8:27

1 Answer 1

5

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! It was because I forgot to to append the script in the inspector and because i was disabling the pic
also i figured out my (probably biggest) problem was that i was trying to find using GameObject.Find and SetActive(false) by putting both in awake at the same time, when i put SetActive(false) in Start() it solved the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.