Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Checking if a game object exists?

Discussion in 'Scripting' started by Joey_Thiesen, Dec 4, 2011.

  1. Joey_Thiesen

    Joey_Thiesen

    Joined:
    Nov 25, 2011
    Posts:
    65
    Is there a way I can use an if statement to see if a prefab is in the scene, and execute various code depending on whether it is?
     
  2. All_American

    All_American

    Joined:
    Oct 14, 2011
    Posts:
    1,528
    Pretty sure you could do that with tags.
     
  3. TheCasual

    TheCasual

    Joined:
    Sep 30, 2010
    Posts:
    1,286
    yup - or even the name of the object will return true if its out there.
     
  4. Joey_Thiesen

    Joey_Thiesen

    Joined:
    Nov 25, 2011
    Posts:
    65
    ....


    How I would I check for that?
     
  5. Joey_Thiesen

    Joey_Thiesen

    Joined:
    Nov 25, 2011
    Posts:
    65
    Help please... I need this to finish my project.
     
  6. All_American

    All_American

    Joined:
    Oct 14, 2011
    Posts:
    1,528
    What are you using js or C#?
     
  7. TheCasual

    TheCasual

    Joined:
    Sep 30, 2010
    Posts:
    1,286
    well it really depends what method as well.

    If you want to find the object by its name, than use this kind of method...

    Code (csharp):
    1.  
    2.   if(GameObject.Find("GameObjectsName")) { //whatever }
    3.  
    Or lf, if you want to add a tag to the gameObject through the inspector, you can call it like this from its tag.


    Code (csharp):
    1.  
    2.   if(GameObject.FindWithTag("GameObjectsTag")) { //whatever }
    3.  

    Either or should work, its relatively simple.
     
  8. Joey_Thiesen

    Joey_Thiesen

    Joined:
    Nov 25, 2011
    Posts:
    65
    Oh right. Wow that's simple. Thanks guys.
     
  9. All_American

    All_American

    Joined:
    Oct 14, 2011
    Posts:
    1,528
    Willc, what goes in the {//whatever}
     
  10. tuckismad

    tuckismad

    Joined:
    Oct 31, 2011
    Posts:
    29
    {//whatever} is where your code goes
     
    Last edited: Dec 4, 2011
  11. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
  12. ThinhHB

    ThinhHB

    Joined:
    Oct 24, 2014
    Posts:
    9
    Try this, tested and work ok for me
    Code (CSharp):
    1. var sceneName = testObject.scene.name;
    2. if (sceneName != null)
    3. {
    4.     // this object is on scene
    5. }
    6. else
    7. {
    8.     // this object is a prefab, not instantiate on any scene
    9. }