| | 1 | | using System.Collections.Generic; |
| | 2 | | using UnityEngine; |
| | 3 | |
|
| | 4 | | namespace DCL.Helpers |
| | 5 | | { |
| | 6 | | [CreateAssetMenu(fileName = "GenericFactory", menuName = "GenericFactory")] |
| | 7 | | public class GenericFactory : ScriptableObject |
| | 8 | | { |
| | 9 | | [System.Serializable] |
| | 10 | | public class Map |
| | 11 | | { |
| | 12 | | public string key; |
| | 13 | | public GameObject prefab; |
| | 14 | | } |
| | 15 | |
|
| | 16 | | public GameObject defaultPrefab; |
| | 17 | | public Map[] items; |
| | 18 | |
|
| | 19 | | private Dictionary<string, GameObject> cachedItems; |
| | 20 | |
|
| | 21 | | private void PrepareCache() |
| | 22 | | { |
| 157 | 23 | | if (cachedItems != null) |
| 155 | 24 | | return; |
| | 25 | |
|
| 2 | 26 | | cachedItems = new Dictionary<string, GameObject>(); |
| 32 | 27 | | for (int i = 0; i < items.Length; i++) |
| | 28 | | { |
| 14 | 29 | | if (!cachedItems.ContainsKey(items[i].key)) |
| | 30 | | { |
| 14 | 31 | | cachedItems.Add(items[i].key, items[i].prefab); |
| | 32 | | } |
| | 33 | | } |
| 2 | 34 | | } |
| | 35 | |
|
| | 36 | | public GameObject Instantiate(string key, Transform parent = null) |
| | 37 | | { |
| 157 | 38 | | PrepareCache(); |
| | 39 | |
|
| 157 | 40 | | GameObject prefab = cachedItems.ContainsKey(key) ? cachedItems[key] : defaultPrefab; |
| 157 | 41 | | if (prefab == null) |
| | 42 | | { |
| 0 | 43 | | Debug.LogError($"Prefab for Key: {key} is null!"); |
| 0 | 44 | | return default; |
| | 45 | | } |
| | 46 | |
|
| 157 | 47 | | return parent == null ? Instantiate(prefab) : Instantiate(prefab, parent); |
| | 48 | | } |
| | 49 | |
|
| | 50 | | public T Instantiate<T>(string key, Transform parent = null) where T : Component |
| | 51 | | { |
| 157 | 52 | | var prefab = Instantiate(key, parent); |
| 157 | 53 | | return prefab == null ? null : prefab.GetComponent<T>(); |
| | 54 | | } |
| | 55 | | } |
| | 56 | | } |