public class SettingsFile: ScriptableObject
{
private static SettingsFile _instance;
public static SettingsFile Instance
{
get
{
if (_instance != null) return _instance;
_instance = Resources.FindObjectsOfTypeAll<SettingsFile>().FirstOrDefault();
if (_instance != null) return _instance;
}
}
If the file is imported from a unity package. This always returns null unless I move the imported file out of the folder to any place in the project. After moving the file anywhere, it finds the instance. Does anyone know of a way around this problem?
1 Like
-
Do not use static accessor on a ScriptableObject. Drag the object into a slot where you want to use it.
-
if you really need to then here is how you can do it safely (I don’t recommend it):
-
if you want to check in Editor that one of these are already exists:
https://docs.unity3d.com/ScriptReference/AssetDatabase.FindAssets.html with the t: search you can check.
But if you want to boot up your static Instance variable, then this way:
#if UNITY_EDITOR
private void OnEnable()
{
EditorApplication.playModeStateChanged += OnPlayStateChange;
}
private void OnDisable()
{
EditorApplication.playModeStateChanged -= OnPlayStateChange;
}
private void OnPlayStateChange(PlayModeStateChange state)
{
if(state == PlayModeStateChange.EnteredPlayMode)
{
OnBegin();
}
}
#else
private void OnEnable()
{
OnBegin();
}
#endif
private void OnBegin()
{
Instance = this;
}
This is working both in the Editor and in the build in theory, unless I didn’t mistype something, because it was from the top of my head.
Have you seen the Unity Unite talk?
“Overthrowing the MonoBehaviour tyranny in a glorious ScriptableObject revolution”.
This is almost exactly the code unity posted.
Its also how steamVR does it but they load it from the Resources folder.
This is a settings file for In editor use only, so I’ll check out the AssetDatabase.findassets
I didn’t realize Resources was a special folder that could be used in any folder like Editor.
I just did what steamVR did, and threw it into a Resources folder, that way I can keep my asset entirely contained in one folder.
If it’s editor only, that makes it even easier. Just use the OnEnable. It runs when you create/load the ScriptableObject. It doesn’t run when you go in play mode.
If this is editor only, it is probably a good idea to protect the entire file with #if UNITY_EDITOR in order to not to build into the runtime.
I saw every ScriptableObject thing, I was play with the a lot. That’s why I came to the conclusion to not to allow static accessor to any of them.