89 lines
2.7 KiB
C#
89 lines
2.7 KiB
C#
using System;
|
|
using System.Reflection;
|
|
using UnityEngine;
|
|
|
|
namespace BrewMonster
|
|
{
|
|
public class AutoInitializer : MonoBehaviour
|
|
{
|
|
private void Awake()
|
|
{
|
|
Initialize();
|
|
}
|
|
|
|
|
|
private void Initialize()
|
|
{
|
|
var interfaceType = typeof(IAutoInitialize);
|
|
|
|
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
|
|
{
|
|
Type[] typesInAssembly;
|
|
try
|
|
{
|
|
typesInAssembly = assembly.GetTypes();
|
|
}
|
|
catch (ReflectionTypeLoadException e)
|
|
{
|
|
typesInAssembly = e.Types;
|
|
}
|
|
|
|
if (typesInAssembly == null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
foreach (var type in typesInAssembly)
|
|
{
|
|
if (type == null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (type.IsAbstract || type.IsInterface)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (!interfaceType.IsAssignableFrom(type))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
object instance = null;
|
|
try
|
|
{
|
|
if (typeof(ScriptableObject).IsAssignableFrom(type))
|
|
{
|
|
instance = ScriptableObject.CreateInstance(type);
|
|
}
|
|
else if (typeof(MonoBehaviour).IsAssignableFrom(type))
|
|
{
|
|
var go = new GameObject(type.Name);
|
|
go.transform.SetParent(transform, worldPositionStays: false);
|
|
instance = go.AddComponent(type);
|
|
}
|
|
else
|
|
{
|
|
instance = Activator.CreateInstance(type);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.LogError($"AutoInitializer: Failed to create instance of {type.FullName}: {ex}");
|
|
continue;
|
|
}
|
|
|
|
try
|
|
{
|
|
(instance as IAutoInitialize)?.Initialize();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.LogError($"AutoInitializer: Failed to initialize {type.FullName}: {ex}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |