Scriptable Objects, how to force Include in Compile / Build without referencing it in the scene?

Hi there, as the title states I’m trying to:

“Include a scriptable object in compiling / not lose it upon compiling without referencing it in the scene.”

Here’s my situation. I have an EventManager and an AchievementManager Singleton, in the form of Scriptable Objects. I use them in the scene with regular AgEventManager.Instance calls. However, if I do not have the object referenced in the scene, upon loading the project and playing for the first time or when testing a Build, I can’t find the singletons.

If I do have them referenced in the scene, everything is fine, it’s just that I’d rather not if possible. :slight_smile:

If you have any idea, please let me know below, it’d be much appreciated!

Looks:

Simple reference holder solution (that I don’t want):
81719-referenceholder.png

Scriptable Object Singleton Code:

using UnityEngine;

// ===================================================================================

public class AgScriptableSingleton<T> : ScriptableObject where T : ScriptableObject
{
    protected static T m_instance;

    // ===============================================================================

    public static T Instance
    {
        get
        {
            _fillInstance();
            return m_instance;
        }
    }

    // ===============================================================================

    private static void _fillInstance()
    {
        if( !m_instance )
        {
            T[] instances = Resources.FindObjectsOfTypeAll<T>();

            if( instances.Length > 0 )
            {
                m_instance = instances[ 0 ];
            }
        }

        if( !m_instance )
        {
#if UNITY_EDITOR
            m_instance = AgScriptableObjectUtility.CreateAsset<T>();
#else
            Debug.LogWarning( "[AgWarning] Cannot use scriptable objects outside of the editor, so the Instance MUST exist beforehand." );
#endif
        }
    }
}

Relative Posts:

http://ivanozanchetta.com/gamedev/unity3d/unity-serialization-behind-scriptableobject/

https://www.reddit.com/r/Unity3D/comments/35kjr3/where_do_instances_of_scriptable_objects_go/

Anything included in a folder named Resources is included in your build. Otherwise, anything that is not referenced (even indirectly) by a scene in your build settings will be stripped from the build. You can read more here, but in general use of the Resources folder is discouraged.

I would recommend you continue to include a reference to your singleton (e.g. on some manager GameObject in your scene) and register the singleton in its OnEnable() callback rather than using Resources.FindObjectsOfTypeAll().

protected virtual void OnEnable()
{
    // maybe log a warning here if instance is not null
    m_instance = this;
}