Movement/Runtime/Config/MovementFactory.cs

62 lines
1.7 KiB
C#
Raw Permalink Normal View History

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