using System.Collections.Generic; using UnityEngine; namespace VoxelBusters.CoreLibrary { public static class ComponentUtility { #region Static methods public static T AddComponentIfNotFound(this GameObject gameObject) where T : Component { var component = gameObject.GetComponent(); if (null == component) { component = gameObject.AddComponent(); } return component; } public static T GetComponentInPredecessor(this MonoBehaviour monoBehaviour) where T : Component { var parentTransform = monoBehaviour.transform.parent; while (parentTransform) { var targetComponent = parentTransform.GetComponent(); if (targetComponent) { return targetComponent; } parentTransform = parentTransform.parent; } return null; } public static T[] GetComponentsInChildren(this Component component, bool includeParent, bool includeInactive) where T : Component { var components = component.GetComponentsInChildren(includeInactive); if (includeParent) { return components; } else { var childComponents = new List(); foreach (var item in components) { if (item.transform != component.transform) { childComponents.Add(item); } } return childComponents.ToArray(); } } #endregion } }