I’ve got a ScriptableObject called UnlockSettings that I want to use as a Singleton. The code is like this:
using UnityEngine;
using System.Linq;
public class UnlockSettings : ScriptableObject
{
private static UnlockSettings _instance;
public static UnlockSettings Instance
{
get
{
if (!_instance)
{
_instance = Resources.FindObjectsOfTypeAll<UnlockSettings>().FirstOrDefault();
}
return _instance;
}
}
int someInt;
string someString;
}
This ScriptableObject is designed to just contain a bunch of strings and ints that I’ll need to reference in other scripts, and I’ve got an .asset file I’ve created which sits in the root of /Assets with all the data entered in.
But I’m having some issues using it. If I close Unity completely, and open it again, hit play, any object that uses UnlockSettings.Instance won’t work as FindObjectsOfTypeAll is returning null as it can’t find itself.
Oddly if I just click on the asset file once, and hit play again, now everything works.
I think this is something to do with the way ScriptableObjects are loaded into memory? Before I click on the object it’s not in memory yet, so FindObjectsOfTypeAll can’t detect it.
Am I doing something wrong, if so what is the best way of doing this?