5 using System.Collections.Generic;
23 public static T EnsureComponent<T>(
this GameObject gameObject) where T : Component
25 T foundComponent = gameObject.GetComponent<T>();
26 if (foundComponent == null)
28 return gameObject.AddComponent<T>();
31 return foundComponent;
41 public static T EnsureComponent<T>(
this Component component) where T : Component
43 return EnsureComponent<T>(component.gameObject);
54 foreach (var item
in root.GetComponentsInChildren<Transform>())
56 action(item.gameObject);
67 public static T FindAncestorComponent<T>(
this GameObject gameObject,
bool includeSelf =
true) where T : Component
69 return gameObject.transform.FindAncestorComponent<T>(includeSelf);
79 public static T FindAncestorComponent<T>(
this Component component,
bool includeSelf =
true) where T : Component
81 return component.transform.FindAncestorComponent<T>(includeSelf);
91 public static T FindAncestorComponent<T>(
this Transform startTransform,
bool includeSelf =
true) where T : Component
93 foreach (Transform transform
in startTransform.EnumerateAncestors(includeSelf))
95 T component = transform.GetComponent<T>();
96 if (component != null)
111 public static IEnumerable<Transform>
EnumerateAncestors(
this Transform startTransform,
bool includeSelf)
115 startTransform = startTransform.parent;
118 for (Transform transform = startTransform; transform != null; transform = transform.parent)
120 yield
return transform;
130 public static void ForEachComponent<T>(
this GameObject g, Action<T> action)
132 foreach (T i
in g.GetComponents<T>())