using UnityEngine; using System.Collections.Generic; public class ComponentCache { public enum LogMessageLevel { all, error, none} LogMessageLevel logMessageLevel = LogMessageLevel.error; private GameObject _gameObject; private List _components = new List(); public ComponentCache(GameObject gameObject) { _gameObject = gameObject; } public ComponentCache(GameObject gameObject , LogMessageLevel messageLevel) { _gameObject = gameObject; logMessageLevel = messageLevel; } public T GetComponent() where T : Component { for (int i = 0; i < _components.Count; i++) { if (_components[i].GetType() == typeof(T)) { Log(typeof(T).Name + " found in cache."); return _components[i] as T; } } Component c = _gameObject.GetComponent(); if (c != null) { Log(typeof(T).Name + " added to cache."); _components.Add(c); return c as T; } LogError(typeof(T).Name + " not found."); return null; } public void DestroyAllComponentsOfType() where T : Component { bool destroyed = false; for (int i = 0; i < _components.Count; i++) { if (_components[i].GetType() == typeof(T)) { Log(typeof(T).Name + " removed from cache and destroyed."); Object.DestroyImmediate(_components[i]); _components.RemoveAt(i); destroyed = true; } } if (!destroyed) LogError(typeof(T).Name + " not found."); } public void DestroyComponent(Component component) { bool destroyed = false; for (int i = 0; i < _components.Count; i++) { if (_components[i] == component) { Log(component.GetType().Name + " removed from cache and destroyed."); Object.DestroyImmediate(_components[i]); _components.RemoveAt(i); destroyed = true; } } if (!destroyed) LogError(component.GetType().Name + " not found."); } void Log(string message) { if (logMessageLevel == LogMessageLevel.all) Debug.Log(message); } void LogError(string message) { if (logMessageLevel != LogMessageLevel.none) Debug.LogError(message); } } // Test Case /* using UnityEngine; using UnityEngine.Assertions; public class TestCacheComponent : MonoBehaviour { public ComponentCache cc; AudioSource asrc1; void Start() { cc = new ComponentCache(gameObject , ComponentCache.LogMessageLevel.all); Debug.LogWarning("Test Cache"); cc.GetComponent(); cc.GetComponent(); cc.DestroyAllComponentsOfType(); Debug.LogWarning("Add component test"); asrc1 = gameObject.AddComponent(); asrc1.mute = true; AudioSource testAs = cc.GetComponent(); if (testAs != asrc1) Debug.LogError("Retrieved component not the same?"); testAs = cc.GetComponent(); if (testAs != asrc1) Debug.LogError("Retrieved component not the same?"); Debug.LogWarning("Adding second component"); AudioSource asrc2 = gameObject.AddComponent(); Debug.LogWarning("Destroying first component"); cc.DestroyComponent(asrc1); cc.GetComponent(); cc.GetComponent(); Assert.IsNull(asrc1); Assert.IsNotNull(asrc2); } bool doOnce = true; void Update() { if (doOnce && asrc1 == null) { doOnce = false; Debug.LogWarning("AudioSource 1 is now null"); } } } */