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