Keep just one gameManager and destroy clones?

Hey guys Im having a little trouble with some big scripts I created today, I know the answer is something simple but I can not figure it out.

I created a GameManager object without collider,render etc…
its just created to run a script that needs to be alive in all scenes (I used DontDestroyOnLoad) and this keep my variables saved.

The problem is that the gameManager is a required gameObject by another script (it´s part
of a variable used to store the script and use"GetComponent" later ) so when I load other scenes it works fine (keep my vars saved) but when I return to the scenes where the script was required there are TWO GameManager objects. (it seems like it got duplicated because it was required by the other script… seems weird)

My question How do I keep just one GameManager at a time and automatically set it to the variable that requires it on the inspector via script?

I hope you guys understand what I mean, it was hard to explain…

Well there’s a few ways. The cleanest would probably to fully implement the singleton pattern. Otherwise a dirty way could look like this:

//MyManager.js
function Awake():void
{
    if(FindObjectsOfType(MyManager).length > 1)
    {
        //Destroy(this);
        //Destroy(gameObject);
    }

}

Basically just self-destruct if more than one object of the manager type is found.

Another alternative is to not use DontDestroyOnLoad and declare as static the variables you want to keep: static variables are created only once when the program starts, and are destroyed only when it finishes, even if the script where they are declared is destroyed and recreated each new level. The only precaution is to not initialize the variables at Start or Awake, only in their declarations, like this:

static var points: float = 0;
static var time: float = 0;

The variables above will be created and initialized only when the program begins. They survive and keep their values when you load a new level, no matter how much instances of this script are around (even 0 instances!).