115 lines
3.5 KiB
C#
115 lines
3.5 KiB
C#
using BrewMonster.Network;
|
|
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Reflection;
|
|
using UnityEngine;
|
|
|
|
namespace BrewMonster
|
|
{
|
|
public class AutoInitializer : MonoBehaviour
|
|
{
|
|
private List<IAutoInitialize> _autoInitializers = new();
|
|
|
|
private void Awake()
|
|
{
|
|
Initialize();
|
|
EC_Game.Init();
|
|
SkillStubs.Init();
|
|
DontDestroyOnLoad(gameObject);
|
|
}
|
|
|
|
private IEnumerator Start()
|
|
{
|
|
yield return null;
|
|
EC_Game.InitSettingAudio();
|
|
}
|
|
|
|
void OnDestroy()
|
|
{
|
|
BMLogger.Log("AutoInitializer: OnDestroy called, disposing auto initializers");
|
|
foreach (var autoInitializer in _autoInitializers)
|
|
{
|
|
autoInitializer.Dispose();
|
|
}
|
|
_autoInitializers.Clear();
|
|
}
|
|
|
|
|
|
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();
|
|
_autoInitializers.Add(instance as IAutoInitialize);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.LogError($"AutoInitializer: Failed to initialize {type.FullName}: {ex} {ex.StackTrace}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|