using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using Syntriax.Modules.Movement.VariableMovement; namespace Syntriax.Modules.Movement.Config { public class VariableMovementFactory : MonoBehaviour { private const string Name = "Variable Movement Factory"; private const int InitialCapacity = 64; private const string ResourceDirectoryToCollections = "Modules/Syntriax/Movement/Variable Movement/Collections/"; private static VariableMovementFactory _instance = null; public static VariableMovementFactory Instance { get { if (_instance == null) _instance = new GameObject(Name).AddComponent(); return _instance; } } private Dictionary _collections = null; public Dictionary Collections { get { if (_collections == null) Initialize(); return _collections; } } private void Start() { if (_instance == this) return; Destroy(this); } public void Initialize() { if (_collections == null) _collections = new Dictionary(InitialCapacity); Reset(); foreach (TextAsset definitionTextAsset in UnityEngine.Resources.LoadAll(ResourceDirectoryToCollections)) AddToFactoryWithJSON(definitionTextAsset.text); } public void AddToFactoryWithJSON(string definitionJSONText) { VMCollection collectionDefinition = JsonUtility.FromJson(definitionJSONText); AddCollectionToFactory(collectionDefinition); } public void Reset() => _collections?.Clear(); public void AddCollectionsToFactory(List collections) { foreach (VMCollection collection in collections) AddCollectionToFactory(collection); } public void AddCollectionToFactory(VMCollection collection) { if (Collections.ContainsKey(collection.Name)) throw new System.ArgumentException($"{collection.Name} is already in the {Name}"); Collections.Add(collection.Name, collection); } // public Component AddToGameObject(GameObject gameObject, string name) // { // if (!Collections.ContainsKey(name)) // throw new ArgumentException($"The key \"{ name }\" does not exists in the current Movement Factory"); // return gameObject.AddComponent(Collections[name]); // } public string GetTypeName(Type type) { if (string.IsNullOrEmpty(type.Namespace)) return type.Name; return $"{type.Namespace}.{type.Name}"; } #if UNITY_EDITOR public void SaveCollection(VMCollection collection) { string jsonText = JsonUtility.ToJson(collection, true); string path = $"Assets/Resources/{ResourceDirectoryToCollections}{collection.Name}.json"; System.IO.File.WriteAllText(path, jsonText); } #endif } }