Search code examples
c#unity-game-enginescriptable-object

Unity : Singleton ScriptableObjects resets after play


I have a singleton class that contains general information about my game.

public class GeneralGameData : ScriptableObject
{
    private static GeneralGameData _currentGeneralGameData;

    public static GeneralGameData CurrentGeneralGameData
    {
        get
        {
            if (_currentGeneralGameData == null)
            {
                _currentGeneralGameData = CreateInstance<GeneralGameData>();
            }

            DontDestroyOnLoad(_currentGeneralGameData);

            return _currentGeneralGameData;
        }
    }

    public string GameName;

    public string GameVersion;

}

This class has no presents in the scene.

I also have a window to show and change that

 public class GeneralGameDataMenuItem : EditorWindow
{
    [MenuItem("CoreMaker/GeneralGameData")]
    private static void _generalGameData()
    {
        GetWindow<GeneralGameDataMenuItem>("GeneralGameData");
    }

    void OnGUI()
    {
        GeneralGameData.CurrentGeneralGameData.GameName = EditorGUILayout.TextField("GameName", GeneralGameData.CurrentGeneralGameData.GameName);
        GeneralGameData.CurrentGeneralGameData.GameVersion = EditorGUILayout.TextField("GameVersion", GeneralGameData.CurrentGeneralGameData.GameVersion);

        EditorUtility.SetDirty(GeneralGameData.CurrentGeneralGameData);
    }
}

The problem is that it wont save my changes after i hit play or restart unity. any solutions??


Solution

  • A ScriptableObject is intended to be saved as an asset. Add the line [CreateAssetMenu(menuName = "MyGame/GeneralGameData")] above your ScriptableObject class declaration, then right click in the project pane, click Create > MyGame > GeneralGameData. Fill in all the fields you need. Any script that needs to reference it can just add a public field of type GeneralGameData and add that asset in the inspector.