- Home /
 
Best way to detect if a prefab is already in the scene?
Hello again :). I have got several scripts, like a music player script and a GameState Script, Which I would like to keep active throughout all scene's. I Have managed to do this with "don't destroy on load". My problem is when I get back to the main menu - they re-instantiate again with scene... I have tried checking for objects with the same tag - and deleting the game object if another is found already in place - yet it's not working... Somehow I feel like is stupidly easy... This is what I've got at the moment :
 GameObject thisDup = GameObject.FindGameObjectWithTag("System");
 if(thisDup)
 {
     Destroy(gameObject);
 }
 
              Answer by chemicalvamp · Nov 06, 2011 at 11:05 AM
 Hmm try this out:
     void Awake() 
     {
         public GameObject[] duplicates = GameObject.FindGameObjectsWithTag("System");
         foreach (GameObject gameObject in duplicates)
         {
             Destroy(gameObject);
         }
     }
 
 
               Might be some errors, threw it together quick in notepad
You can't have a variable called gameObject because it's the name of a property. Change it's name to anything else:
    foreach (GameObject dup in duplicates)
    {
        Destroy(dup);
    }
 You should also do it at Start, because Awake may occur in this particular object before the duplicate has been created. 
                 You can have a local variable named gameObject, it will just shadow the property.
Yeah, having a local variable named gameObject will technically work, but that doesn't stop it being disgusting.
True words :D. It's just bad practise cause it can produce unexpected results. In some cases you might want to hide a property but it should be avoided since it makes the code very hard to read. If you work with other programmers you should write clear code.
Anyways, it's a solution ;)
Your answer