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 _types = null; public Dictionary Types { get { if (_types == null) Initialize(); return _types; } } private Func predicate = type => !type.IsAbstract && type.IsSubclassOf(typeof(MonoBehaviour)); private void Start() { if (FactorySingleton.Instance == this) return; Destroy(this); } public override void Initialize() { if (_types == null) _types = new Dictionary(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]); } } }