# How to check if an GameObject exists in Unity2D? (Javascript)

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?

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

bool playerexists = (GameObject.Find("player") != null)

• But is there a way to not use a tag? That would be better. – ElPolloLoco999 Aug 21 '15 at 10:28
• edited: added find (no tag) – dnk drone.vs.drones Aug 21 '15 at 10:32

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!!!

• 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. – Draco18s Dec 30 '15 at 19:36
• 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. – Danoweb Dec 30 '15 at 19:49
• 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. – Draco18s Dec 30 '15 at 19:51
• 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. ;) – Draco18s Dec 30 '15 at 19:53