Movement/Runtime/Config/MovementFactory.cs

62 lines
1.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Syntriax.Modules.Factory;
using UnityEngine;
namespace Syntriax.Modules.Movement.Config
{
public class MovementFactory : FactoryBase
{
private const int InitialCapacity = 64;
private Dictionary<string, Type> _types = null;
public Dictionary<string, Type> Types
{
get
{
if (!IsInitialized)
Initialize();
return _types;
}
}
private Func<Type, bool> predicate = type => !type.IsAbstract && type.IsSubclassOf(typeof(MonoBehaviour));
private void Start()
{
if (FactorySingleton<MovementFactory>.Instance == this)
return;
Destroy(this);
}
protected override void OnFactoryInitialize()
{
if (_types == null)
_types = new Dictionary<string, Type>(InitialCapacity);
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
AddAssemblyToFactory(assembly);
}
protected override void OnFactoryReset() => _types?.Clear();
public void AddAssemblyToFactory(Assembly assembly)
{
foreach (Type type in assembly.GetTypes().Where(predicate))
Types.Add(type.FullName, type);
}
public Component AddToGameObject(GameObject gameObject, string name)
{
if (!Types.ContainsKey(name))
throw new ArgumentException($"The key \"{name}\" does not exists in the current {nameof(MovementFactory)}");
return gameObject.AddComponent(Types[name]);
}
}
}