How to fix this error?

Hi all,
I currently have an error that doesn’t actually do anything but keep showing up when I press jump button before 6 seconds.
I explain the situation…
In my game, on the first tutorial scene, I have a jump button with an OnClick(), that starts a function which change a GameObject (text) from a text to another text.
This GameObject (text) appears after 6 seconds.
If I press the jump button before those 6 seconds, nothing happens but I get the error that it obviously doesn’t find the gameobject. If I press the jump button after 6 seconds, I don’t get any error.
Any way to fix it?

Check if the object is null

GameObject myText = GameObject.Find("MyCoolText");
if (myText != null)
    myText.GetComponent<Text>().text = "Jumped!";

Post your error. Post your code.

Honestly, if it’s an object in the scene, you should be able to just hook it into a variable. GameObject.Find is horrible to use, so hook it in directly rather than trying to find it, which if you are, and it’s not active, that is why it doesn’t work.

Error :
NullReferenceException : Object reference not set to an instance of an object.
The following is attached to the JumpButton.
3320616--258380--upload_2017-12-12_21-11-11.png

public void JumpTutorial()
    {
        if (GameObject.Find("TryToJump").activeInHierarchy == true)
        {
            GameObject.Find("TryToJump").GetComponent<Text>().text = "Well done! ";
        }
    }

Atm I haven’t time to test your solutions, I will test them tomorrow, I wanted to post the details you asked anyway.
Thank you.

Yeah, GameObject.Find only finds active objects. Which means it’s returning null, then you’re trying to see if it’s active, but it’s null, which gives you the null error. It would be better to just tie the text object into a variable instead of trying to find it over and over again.

Otherwise, you will have to check if it’s null as was suggested, just not the best way.

Friends don’t let friends use GameObject.Find…

Assign the TryToJump GameObject a unique tag, such as “TryToJump”, and do something like this.

public void JumpTutorial()
    {
        GameObject jumpObject = GameObject.FindGameObjectWithTag("TryToJump");
        if (jumpObject != null)
        {
            jumpObject.GetComponent<Text>().text = "Well done! ";
        }
    }
1 Like

haha, I like that “friends don’t let friends…”. Personally, I like to even avoid Tag/Type when possible; which is nearly always =)
Those methods can seem “fast” and easy to write up, to get whatever you want, but a little practice – along with hopefully a bit of understanding why other options are better – leads to better days ahead. :slight_smile: