Singleton ScriptableObject unable to Find itself, returns null
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;
}
}
}
I've ensure there is 1 instance of UnlockSettings asset in my Project window, in the root of /Assets. A strange thing happens where Resources.FindObjectsOfTypeAll will null.
What seems to fix it temporarily is if I actually Click on the UnlockSettings asset file (which brings it up on the Inspector) and hit Play again, then it works, until eventually it doesn't again.
What's going on here?
Answer by UnityCoach · Jul 25, 2017 at 08:43 AM
From the docs
All assets that are in a folder named "Resources" anywhere in the Assets folder can be accessed via the Resources.Load functions. Multiple "Resources" folders may exist and when loading objects each will be examined.
Interesting idea by the way.
Answer by Radagaisus · Feb 01, 2019 at 05:18 PM
My guess is that the ScriptableObject is not loaded, since it’s not referenced explicitly in the scene. Clicking on it in the editor loads it, and so temporarily fixes the issue. I couldn’t find a nicer fix than explicitly referencing the ScriptableObject in the scene.