using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace Unity.XR.CoreUtils { /// /// Special utility class for getting components in the editor without allocations. /// /// The type of component for which to be searched. public static class ComponentUtils { // Local method use only -- created here to reduce garbage collection. Collections must be cleared before use static readonly List k_RetrievalList = new List(); /// /// Gets a single component of type T using the non-allocating GetComponents API. /// /// The GameObject from which to get the component. /// The component, if one exists. public static T GetComponent(GameObject gameObject) { var foundComponent = default(T); // k_RetrievalList is cleared by GetComponents gameObject.GetComponents(k_RetrievalList); if (k_RetrievalList.Count > 0) foundComponent = k_RetrievalList[0]; return foundComponent; } /// /// Gets a single component of type T using the non-allocating GetComponentsInChildren API. /// /// The GameObject from which to get the component. /// The component, if one exists. public static T GetComponentInChildren(GameObject gameObject) { var foundComponent = default(T); // k_RetrievalList is cleared by GetComponentsInChildren gameObject.GetComponentsInChildren(k_RetrievalList); if (k_RetrievalList.Count > 0) foundComponent = k_RetrievalList[0]; return foundComponent; } } /// /// Utility class for working with Components. /// public static class ComponentUtils { /// /// Gets a component from a GameObject. Optionally, adds a new component and returns it /// if a component of the specified type does not already exist. /// /// The parent GameObject. /// Whether to add a new component of the given type, if one does not already exist. /// The type of component to get or add. /// The new or retrieved component. public static T GetOrAddIf(GameObject gameObject, bool add) where T : Component { var component = gameObject.GetComponent(); #if UNITY_EDITOR if (add && component == null) component = Undo.AddComponent(gameObject); #else if (add && component == null) component = gameObject.AddComponent(); #endif return component; } } }