using UnityEngine; using System.Collections; using System.Collections.Generic; public class SSCacheManager : MonoBehaviour { Dictionary> m_Cache = new Dictionary>(); Dictionary> m_Using = new Dictionary>(); private static SSCacheManager m_Instance; public static SSCacheManager Instance { get { if (m_Instance == null) { m_Instance = Object.FindObjectOfType(typeof(SSCacheManager)) as SSCacheManager; if (m_Instance == null) { GameObject go = new GameObject("CacheManager"); DontDestroyOnLoad(go); m_Instance = go.AddComponent(); } } return m_Instance; } } private void Awake () { if (m_Instance == null) { m_Instance = this; DontDestroyOnLoad (gameObject); } else { Destroy (gameObject); } } private void OnEnable () { if (m_Instance == null) { m_Instance = this; } } private void OnDestroy () { if (m_Instance == this) { m_Instance = null; } } public void PreLoad(GameObject prefab, int quantity) { string n = prefab.name; if (!m_Cache.ContainsKey (n)) { m_Cache.Add (n, new List ()); } for (int i = 0; i < quantity; i++) { GameObject go = CreateObject (n, prefab); go.SetActive (false); } } public GameObject InstantiateObject(GameObject prefab) { string n = prefab.name; if (!m_Cache.ContainsKey (n)) { m_Cache.Add (n, new List ()); } if (m_Cache[n].Count == 0) { CreateObject (n, prefab); } // Remove from cache GameObject r = m_Cache [n] [0]; m_Cache [n].RemoveAt (0); // Add to using if (!m_Using.ContainsKey (n)) { m_Using.Add (n, new List ()); } m_Using [n].Add (r); // Active object r.SetActive (true); return r; } public void DestroyObject(GameObject go, float time = 0) { StartCoroutine (IEDestroyObject (go, time)); } private IEnumerator IEDestroyObject(GameObject go, float time) { if (time > 0) { yield return new WaitForSeconds (time); } foreach (var item in m_Using) { if (item.Value.Contains (go)) { // Deactive object go.SetActive (false); go.transform.parent = transform; // Remove from using m_Using [item.Key].Remove (go); // Add to cache m_Cache [item.Key].Add (go); break; } } } public void Clear() { // Clear cache foreach (var cache in m_Cache) { foreach (var item in cache.Value) { Destroy (item); } } m_Cache.Clear (); // Warning if using if (m_Using.Count > 0) { Debug.LogWarning ("Some of gameobjects which have been using will not be destroyed"); } } private GameObject CreateObject(string key, GameObject prefab) { GameObject go = Instantiate (prefab) as GameObject; m_Cache[key].Add (go); go.transform.parent = transform; go.transform.localScale = Vector3.zero; go.transform.localPosition = Vector3.zero; go.transform.localRotation = Quaternion.identity; return go; } }