Movement/Config/MovementFactory.cs

64 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 (_types == null)
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);
}
public override void Initialize()
{
if (_types == null)
_types = new Dictionary<string, Type>(InitialCapacity);
Reset();
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
AddAssemblyToFactory(assembly);
}
public override void Reset() => _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]);
}
}
}