using System; using System.Collections.Generic; using UnityEngine; namespace D2D.Utilities { public class SmartScript : MonoBehaviour { public T Get(bool canBeNull = true) where T : Component => Single(GetComponent, canBeNull); public T[] Gets(bool canBeNull = true) where T : Component => Many(GetComponents, canBeNull); public T ChildrenGet(bool canBeNull = true) where T : Component => Single(GetComponentInChildren, canBeNull); public T[] ChildrenGets(bool canBeNull = true) where T : Component => Many(GetComponentsInChildren, canBeNull); public T ParentGet(bool canBeNull = true) where T : Component => Single(GetComponentInParent, canBeNull); public T[] ParentGets(bool canBeNull = true) where T : Component => Many(GetComponentsInParent, canBeNull); public T Find(bool canBeNull = true) where T : Component => Single(FindObjectOfType, canBeNull); public T[] Finds(bool canBeNull = true) where T : Component => Many(FindObjectsOfType, canBeNull); private T Single(Func getComponentMethod, bool canBeNull) where T : Component { var result = getComponentMethod?.Invoke(); if (!canBeNull && result == null) throw new Exception($"Single NOT found {typeof(T).FullName} for {gameObject.name}!"); return result; } private T[] Many(Func getComponentMethod, bool canBeNull) where T : Component { var result = getComponentMethod?.Invoke(); if (!canBeNull && result == null) throw new Exception($"Many NOT found {typeof(T).FullName} for {gameObject.name}!"); return result; } } }