overmelted/Assets/ConjureOS/Scripts/GlobalObject/ConjureGlobalObjectInitializer.cs

61 lines
1.9 KiB
C#

using ConjureOS.ArcadeMenu;
using UnityEngine;
using UnityEngine.SceneManagement;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace ConjureOS.GlobalObject
{
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
public static class ConjureGlobalObjectInitializer
{
public const string GlobalObjectName = "ConjureGlobalObject";
public static readonly System.Type[] GlobalObjectComponentTypes =
{
typeof(ConjureArcadeMenuController)
};
#if UNITY_EDITOR
static ConjureGlobalObjectInitializer()
{
if (!EditorApplication.isPlayingOrWillChangePlaymode)
{
InitializeGlobalObject();
}
}
#endif
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
private static void InitializeGlobalObject()
{
GameObject globalObject = GameObject.Find(GlobalObjectName);
if (!globalObject)
{
globalObject = new GameObject(GlobalObjectName);
}
InitializeComponentsOnGlobalObject(globalObject);
}
private static void InitializeComponentsOnGlobalObject(GameObject globalObject)
{
foreach (var globalObjectComponentType in GlobalObjectComponentTypes)
{
if (globalObject.GetComponent(globalObjectComponentType))
{
continue;
}
if (!globalObjectComponentType.IsSubclassOf(typeof(MonoBehaviour)))
{
Debug.LogError($"ConjureOS: Cannot add component '{nameof(globalObjectComponentType.FullName)}' to global object because it is not a component.");
continue;
}
globalObject.AddComponent(globalObjectComponentType);
}
}
}
}