Editor singleton

Hi,

I’m trying to find a pattern that works for having a singleton class that shares data between the editor and the game. Here’s what my third attempt looks like:

public class SingletonScriptableObject<T> : ScriptableObject where T : ScriptableObject
{
    private static T s_Instance = null;

    public static T Instance
    {
        get
        {
            return GetInstance();
        }
    }

    private static T GetInstance()
    {
#if UNITY_EDITOR
        // If there's no instance, load or create one
        if( s_Instance == null )
        {
            string assetPathAndName = GeneratePath();

            // Check the asset database for an existing instance of the asset
            T asset = null;
            asset = AssetDatabase.LoadAssetAtPath( assetPathAndName, typeof( ScriptableObject ) ) as T;

            // If the asset doesn't exist, create it
            if( asset == null )
            {
                asset = ScriptableObject.CreateInstance<T>();
                AssetDatabase.CreateAsset( asset, assetPathAndName );
                AssetDatabase.SaveAssets();
            }

            s_Instance = asset;
        }
#endif

        return s_Instance;
    }

    public void SaveInstanceData()
    {
#if UNITY_EDITOR
        EditorUtility.SetDirty( s_Instance );
        AssetDatabase.SaveAssets();
#endif
    }

    private static string GeneratePath()
    {
        return "Assets/Singleton " + typeof( T ).ToString() + ".asset";
    }
}

And is used thusly:

public class MySingleton : SingletonScriptableObject<MySingleton>
{
blahblahblah
}

The problem with this method is that object references don’t get saved into the asset. Well, they do actually, but when the asset is loaded in game all object references are null.

So, what’s the best way to have a singleton class that lets you save data set in the editor and load it during the game? I only care about this working if the game is run inside the editor, this code will all be excluded during release builds.

-D

Sure its not getting saved and that the problem is not the lack of AssetDatabase.Refresh(); to pick the change up?

Yep, if I save everything and restart Unity, the object reference is invalid. I imagine it has something to do with assets referring to instances of objects in a specific scene but the asset is loaded in a different scene. Seems broken but oh well.

I just made everything use an instance of a dummy game-object. I was hoping to be able to save changes from the game into the asset, but oh well.

Thanks!

-D