Movement/Config/MovementFactory.cs

72 lines
1.9 KiB
C#
Raw 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
{
if (_types == null)
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 13:51:55 +03:00
public override void Initialize()
2022-03-17 22:12:09 +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-11-21 13:51:55 +03:00
public override 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-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]);
}
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
}
}
}