using System.Collections.Generic; using UnityEngine; using UnityObject = UnityEngine.Object; #if UNITY_EDITOR using UnityEditor; #endif namespace Unity.XR.CoreUtils { /// /// Utility methods for working with UnityEngine types. /// public static class UnityObjectUtils { /// /// Calls the proper Destroy method on an object based on if application is playing. /// /// /// In Play mode or when running your built application, this function calls . /// /// In the Editor, outside of Play mode, this function calls . /// /// Object to be destroyed. /// Whether to record and undo operation for the destroy action. public static void Destroy(UnityObject obj, bool withUndo = false) { if (Application.isPlaying) { UnityObject.Destroy(obj); } #if UNITY_EDITOR else { if (withUndo) Undo.DestroyObjectImmediate(obj); else UnityObject.DestroyImmediate(obj); } #endif } /// /// Returns a component of the specified type that is associated with an object, if possible. /// /// /// If the is the requested type, then this function casts it to /// type T and returns it. /// /// If is a , then this function returns /// the first component of the requested type, if one exists. /// /// If is a different type of component, this function returns /// the first component of the requested type on the same GameObject, if one exists. /// /// The Unity Object reference to convert. /// The type to convert to. /// A component of type `T`, if found on the object. Otherwise returns `null`. public static T ConvertUnityObjectToType(UnityObject objectIn) where T : class { var interfaceOut = objectIn as T; if (interfaceOut == null && objectIn != null) { var go = objectIn as GameObject; if (go != null) { interfaceOut = go.GetComponent(); return interfaceOut; } var comp = objectIn as Component; if (comp != null) interfaceOut = comp.GetComponent(); } return interfaceOut; } /// /// Removes any destroyed UnityObjects from a list. /// /// The specific type of UnityObject in the dictionary. /// A list of UnityObjects that may contain destroyed objects. public static void RemoveDestroyedObjects(List list) where T : UnityObject { var removeList = CollectionPool, T>.GetCollection(); foreach (var component in list) { if (component == null) removeList.Add(component); } foreach (var entry in removeList) { list.Remove(entry); } CollectionPool, T>.RecycleCollection(removeList); } /// /// Removes any destroyed keys from a dictionary that uses UnityObjects as its key type. /// /// The specific type of UnityObject serving as keys in the dictionary. /// The value type of the dictionary. /// A dictionary of UnityObjects that may contain destroyed objects. public static void RemoveDestroyedKeys(Dictionary dictionary) where TKey : UnityObject { var removeList = CollectionPool, TKey>.GetCollection(); foreach (var kvp in dictionary) { var key = kvp.Key; if (key == null) removeList.Add(key); } foreach (var key in removeList) { dictionary.Remove(key); } CollectionPool, TKey>.RecycleCollection(removeList); } } }