2022-03-17 22:12:09 +03:00
|
|
|
using System;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Linq;
|
|
|
|
using System.Reflection;
|
|
|
|
using UnityEngine;
|
|
|
|
|
|
|
|
namespace Syntriax.Modules.Movement.Config
|
|
|
|
{
|
|
|
|
public class MovementFactory : MonoBehaviour
|
|
|
|
{
|
|
|
|
private const string Name = "Movement Factory";
|
|
|
|
private const int InitialCapacity = 64;
|
|
|
|
|
|
|
|
private static MovementFactory _instance = null;
|
|
|
|
public static MovementFactory Instance
|
|
|
|
{
|
|
|
|
get
|
|
|
|
{
|
|
|
|
if (_instance == null)
|
|
|
|
_instance = new GameObject(Name).AddComponent<MovementFactory>();
|
|
|
|
|
|
|
|
return _instance;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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 (_instance == this)
|
|
|
|
return;
|
|
|
|
|
|
|
|
Destroy(this);
|
|
|
|
}
|
|
|
|
|
2022-03-18 16:04:44 +03:00
|
|
|
public void Initialize()
|
2022-03-17 22:12:09 +03:00
|
|
|
{
|
2022-03-18 16:04:44 +03:00
|
|
|
if (_types == null)
|
|
|
|
_types = new Dictionary<string, Type>(InitialCapacity);
|
|
|
|
|
|
|
|
Reset();
|
2022-03-17 22:12:09 +03:00
|
|
|
|
|
|
|
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
|
|
|
|
AddAssemblyToFactory(assembly);
|
|
|
|
}
|
|
|
|
|
2022-03-18 16:04:44 +03:00
|
|
|
public void Reset() => _types?.Clear();
|
|
|
|
|
2022-03-17 22:12:09 +03:00
|
|
|
public void AddAssemblyToFactory(Assembly assembly)
|
|
|
|
{
|
|
|
|
foreach (Type type in assembly.GetTypes().Where(predicate))
|
|
|
|
Types.Add(GetTypeName(type), type);
|
|
|
|
}
|
|
|
|
|
|
|
|
public Component AddToGameObject(GameObject gameObject, string name)
|
|
|
|
{
|
|
|
|
if (!Types.ContainsKey(name))
|
2022-11-16 20:58:14 +03:00
|
|
|
throw new ArgumentException($"The key \"{name}\" does not exists in the current {Name}");
|
2022-03-17 22:12:09 +03:00
|
|
|
|
|
|
|
return gameObject.AddComponent(Types[name]);
|
|
|
|
}
|
|
|
|
|
2022-11-16 20:58:14 +03:00
|
|
|
public static string GetTypeName(Type type)
|
2022-03-17 22:12:09 +03:00
|
|
|
{
|
|
|
|
if (string.IsNullOrEmpty(type.Namespace))
|
|
|
|
return type.Name;
|
|
|
|
|
2022-11-16 20:58:14 +03:00
|
|
|
return $"{type.Namespace}.{type.Name}";
|
2022-03-17 22:12:09 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|