diff --git a/MrBigsock/Assets/Code/Services/PrefabService.cs b/MrBigsock/Assets/Code/Services/PrefabService.cs new file mode 100644 index 0000000000000000000000000000000000000000..2dab1bbdefca4f823dd3f488fdd05c60b28a9521 --- /dev/null +++ b/MrBigsock/Assets/Code/Services/PrefabService.cs @@ -0,0 +1,86 @@ +using System.Collections; +using System; +using System.Linq; +using System.Collections.Generic; +using System.Reflection; + +using UnityEngine; +using UnityEngine.InputSystem; +using UnityEditor; + +using BigSock.Item; + + +namespace BigSock.Service { + + /* + Service for handling prefabs. + */ + public partial class PrefabService { + /* + The instance to use. + */ + public static readonly PrefabService SINGLETON = new PrefabService(); + + /* + Get a prefab of a name. + */ + public GameObject Get(string name) { + if(_prefabs.TryGetValue(_sanitize(name), out var res)) return res; + return null; + } + + + /* + Create an instance of a prefab. + */ + public GameObject Instance(GameObject obj, Vector3? pos = null) { + var res = MonoBehaviour.Instantiate(obj, pos ?? (Vector3) obj.transform.position, obj.transform.rotation); + return res; + } + public GameObject Instance(string name, Vector3? pos = null) + => Instance(_prefabs[_sanitize(name)], pos); + + /* + Destroy an instance. + */ + public void Destroy(GameObject obj) + => MonoBehaviour.Destroy(obj); + + } + + public partial class PrefabService { + private Dictionary<string, GameObject> _prefabs = new Dictionary<string, GameObject>(); + + private System.Random _rnd = new System.Random(); + + private PrefabService() { + _loadItems(); + } + + /* + Load the items into the dictionary. + Based on: https://stackoverflow.com/a/67670629 + */ + private void _loadItems() { + string[] guids = AssetDatabase.FindAssets( "t:Prefab", new string[] {"Assets/Prefabs"} ); + + var dict = new Dictionary<string, GameObject>(); + + foreach(var guid in guids) { + var path = AssetDatabase.GUIDToAssetPath( guid ); + var name = _sanitize(path.Replace(".prefab", "").Replace("Assets/Prefabs/", "")); + GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>( path ); + + Debug.Log($"[PrefabService._loadItems()] {name}"); + dict[name] = go; + } + + _prefabs = dict; + } + + private string _sanitize(string name) + => name.Replace(" ", "").Replace("_", "").ToLower(); + + } +} \ No newline at end of file diff --git a/MrBigsock/Assets/Code/Services/PrefabService.cs.meta b/MrBigsock/Assets/Code/Services/PrefabService.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..d398e58abc610651e186b702a0e089faefd61bd8 --- /dev/null +++ b/MrBigsock/Assets/Code/Services/PrefabService.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b818d945e9735e643ab67c7190d3ac9f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: