0
\$\begingroup\$

Im making an AI that checks if the player exists or not. How do I check if a certain object exists and put it in a boolean variable?

\$\endgroup\$
1
\$\begingroup\$

try using GameObject.FindGameObjectsWithTag or GameObject.FindWithTag or by name (or namepath) GameObject.Find

bool playerexists = (GameObject.Find("player") != null)
\$\endgroup\$
  • \$\begingroup\$ But is there a way to not use a tag? That would be better. \$\endgroup\$ – ElPolloLoco999 Aug 21 '15 at 10:28
  • \$\begingroup\$ edited: added find (no tag) \$\endgroup\$ – dnk drone.vs.drones Aug 21 '15 at 10:32
1
\$\begingroup\$

Unity tutorials explicitly says that "Gameobject.Find()" is a bad way to do this. It is very resource intensive and is not necessary! Take a Look at Adam Buckner's tutorial on this subject, "communication between scripts and game objects". You can find the article here:

https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/communicating-between-components-gameobjects?playlist=17117

I know you may not be too concerned about effiency at this point, BUT! as you polish this, you will become more and more concerned about it, and this will be a good habit to learn now, instead of attempting to fix a bad habit later!

Hope this helps!!!

\$\endgroup\$
  • \$\begingroup\$ GameObject.Find() is usually fine as long as you're not doing it every frame. Once on startup is usually low-resource-cost enough to go unnoticed. That said, there are still better ways to get a reference most of the time. \$\endgroup\$ – Draco18s Dec 30 '15 at 19:36
  • \$\begingroup\$ Yeah, you "can" do it, but if you watch that tutorial, which is on the UNity3D website itself, he goes into the many many reasons not to do it. He even states they added it as a "last resort" kind of solution. I think unfortunately there are a lot of "self taught" individuals out there, and a lot of instructors who aren't teaching "best practice" but just "I found a way to do it" ... and that's unfortunate. \$\endgroup\$ – Danoweb Dec 30 '15 at 19:49
  • \$\begingroup\$ Which is why I gave you a +1. There are much better solutions than Find() but the complexity of Find() is acceptable in a once-off situation that cannot be solved another way. \$\endgroup\$ – Draco18s Dec 30 '15 at 19:51
  • \$\begingroup\$ A well considered answer is worthy of the reputation the +1 gives. A few more like it and you'll have all of the meaningless points you could ever want. ;) \$\endgroup\$ – Draco18s Dec 30 '15 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.