- Home /
GameObject.Find() sometimes fails, is that okay?
I have several invisible locations that my player has to walk over to complete the game. When she touches one, the next will highlight. I do this by using Find() to find the current helper, ie:
var currentGoalHelper = GameObject.Find("Goal"+currentMissionNum+"Helper");
This works great until the final goal is reached because obviously there are no more to find, so I get a Unity error in the console. Is this okay? Or should I be doing some sort of check first? Or is it okay if a Find() fails? I assume sometimes it just won't find anything right?
The trick is, the Find isn't causing your error. Using the bad Find is causing it.
If you reread the two responses below, you'll see the sequence is: do a Find, check if it worked, use it if it did.
$$anonymous$$eeping error messages out of the console is important for framerate, at least in the editor. Unity is probably smart enough to ignore errors on a build, but I wouldn't count on it.
??? Run-time errors in a build cause a crash or freeze, at least in iOS. The final version of the game must never cause a single red error.
But, as the OP has experienced, an error or two while running in the editor isn't that big a deal. You have to fix them sometime, but not right away. Not unless something is spraying errors. If you aren't sure what to do when they finish the race, an error is as good as anything else, for now.
Answer by Kame Sama · Jun 17, 2014 at 09:12 PM
Yes it's okay if the find fails. To keep your console clean, you can wrap the var currentGoalHelper with a check before trying to access it like :
var currentGoalHelper = GameObject.Find("Goal"+currentMissionNum+"Helper");
if (currentGoalHelper){
//Execute code
}else{
//Don't access currentGoalHelper as it is null
}
Keep in mind that the GameObject.Find function will loop across all your gameObjects in the scene. I would personally keep a reference to your currentMissionNum in a static class to avoid running the GameObject.Find every time you need to access the currentMissionNum.
hope this helps!
Thanks but how will I know the Find() will return false unless I check it?
Answer by Landern · Jun 17, 2014 at 08:38 PM
use an if statement to constrain the code, if currentGoalHelper is null skip the code that is associated withe currentGoalHelper, if it is not null, do what you normally do.
// .. code
if (currentGoalHelper) {
... code that uses currentGoalHelper
}
// .. code
Your answer
Follow this Question
Related Questions
Get all Game Objects near point 2 Answers
Separate objects from GameObject[] group 0 Answers
How to access audio of FindChild Object & play it? Error 0 Answers
Problem with finding animator. 1 Answer
Finding A Rigidbody's Rotation Speed And Direction 2 Answers