singleton, global vars and dontdestroyonload

Hello,

I have troubles carrying on my global vars trough scenes. I change the language setting in my menu ingame, then i launch a scene via a new game button and the setting is gone.

Here is my GlobalVar class:

using UnityEngine;
using System.Collections;

public enum GameDifficulty
{
    Easy,
    Medium,
    Hard
}
;

public enum Language
{
    english,
    french
}
;

public class GlobalVars : Singleton<GlobalVars> {
    protected GlobalVars () {} // guarantee this will be always a singleton only - can't use the constructor!
    
    public GameDifficulty difficulty = GameDifficulty.Medium;
    public Language language = Language.english;

    void awake()
    {
        DontDestroyOnLoad(gameObject);
    }
}

I also have a script in my project which contain a singleton class (used for an audio manager). Maybe it have something to do with this. Both are codes i didn’t wrote myself and I’m so lost! Here it is:

using UnityEngine;
using System.Collections;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour {
    protected static T instance;
    
    //Returns the instance of this singleton
    public static T Instance {
        get {
            if (instance == null) {
                instance = (T)FindObjectOfType(typeof(T));
                if (instance == null) {
                    GameObject container = new GameObject();
                    container.name = typeof(T)+"Container";
                    instance = (T)container.AddComponent(typeof(T));
                }
            }
            return instance;
        }
    }
}

Can you please tell me where i’m wrong?

One issue I see here is that you have a constructor in your GlobalVars class which itself inherits from MonoBehaviour. That is not possible, you need to use Awake or Start.

Also a ctor does not guarantee one instance.

But what you are doing here is not related to persistence of data. There are already answers and even a 1h long video on that topic made by the guy from Unity.

http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/persistence-data-saving-loading

I just finished to watch the tutorial and checked your link also. i think i have pretty much what i need to build my persistent datas. Thanks folks!

Just so i know… the fail here was because it wasn’t static? (cause i tried that but i didn’t worked since it’s instantiated). I don’t really understand because in the wiki page this singleton method is described like a nice way to do it… but because i’m a foreigner and a beginner i may be misunderstood some parts.

edit : now i’m thinking i probably get confused between global variables and persistent datas… which are very different things.

reedit: hahaha i’m so stupid… actually my problem was very easy, i just forgot to put a caps on Awake() :wink:
Anyway i learned some nice stuffs too so i don’t regret.