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

How to prevent the engine load the scene with duplicate object?

Discussion in 'Scripting' started by Rond, Jan 26, 2011.

  1. Rond

    Rond

    Joined:
    Oct 21, 2009
    Posts:
    175
    I'm trying to make a PlayerData with functions to save all the player data using player prefs, but it can't be duplicated during the game, what happens is when i load a scene like: current level=world , load level=house, the world contains the PlayerData object set to dont destroy on load, this way i can make an object that saves whatever happens in the game, but when i load back the level world, it is there, and the PlayerData get duplicated.. How to create a object only if it doesn't exists?
     
  2. Rond

    Rond

    Joined:
    Oct 21, 2009
    Posts:
    175
    I've tried this way, but when i load a level that already contains the same gameobject it deletes the old, and the first gameobject cant be deleted:

    Code (csharp):
    1.  
    2. function Awake () {
    3.     if(GameObject.FindWithTag(gameObject.tag)  GameObject.FindWithTag(gameObject.tag) != gameObject){
    4.         for (a in GameObject.FindGameObjectsWithTag(gameObject.tag))
    5.         {
    6.             if(a.GetInstanceID != gameObject.GetInstanceID) Destroy(a);
    7.         }
    8.     }
    9.  
    10.     DontDestroyOnLoad(transform.gameObject);
    11. }
    12.  
    Any one knows how to prevent the load level to create duplicated gameobjects?
    Thanks.
     
  3. seon

    seon

    Joined:
    Jan 10, 2007
    Posts:
    1,441
    You have your playerData GO load in a level before any of the game/world levels and DONT have a new playerData GO in each game/world level. Like a setup level where everything you need to stay persistent across the entire game/world is initialised only once.

    That would be the easiest and cleanest way of doing it.
     
  4. Rond

    Rond

    Joined:
    Oct 21, 2009
    Posts:
    175
    Hehe, thanks, it works perfect!
     
  5. netlander

    netlander

    Joined:
    Nov 22, 2011
    Posts:
    28
    The problem I am having is that when I come back the the level where the "global" GOs have been created, they are duplicated as part of the level creation process.

    Still trying to find an efficient way of getting these GOs reused throughout the game...

    Checking for the GOs duplicates and destroying them as done above seems to defeat the purpose as the creation and destruction is probably more expensive then replicating the GOs when you need them...

    Paul