AR Design
UBC EML collab with UBC SALA - visualizing IoT data in AR
ComponentExtensions.cs
Go to the documentation of this file.
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // Licensed under the MIT License. See LICENSE in the project root for license information.
3 
4 using System;
5 using System.Collections.Generic;
6 using UnityEngine;
7 
8 namespace HoloToolkit.Unity
9 {
14  public static class ComponentExtensions
15  {
23  public static T EnsureComponent<T>(this GameObject gameObject) where T : Component
24  {
25  T foundComponent = gameObject.GetComponent<T>();
26  if (foundComponent == null)
27  {
28  return gameObject.AddComponent<T>();
29  }
30 
31  return foundComponent;
32  }
33 
41  public static T EnsureComponent<T>(this Component component) where T : Component
42  {
43  return EnsureComponent<T>(component.gameObject);
44  }
45 
51  public static void ApplyToHierarchy(this GameObject root, Action<GameObject> action)
52  {
53  action(root);
54  foreach (var item in root.GetComponentsInChildren<Transform>())
55  {
56  action(item.gameObject);
57  }
58  }
59 
67  public static T FindAncestorComponent<T>(this GameObject gameObject, bool includeSelf = true) where T : Component
68  {
69  return gameObject.transform.FindAncestorComponent<T>(includeSelf);
70  }
71 
79  public static T FindAncestorComponent<T>(this Component component, bool includeSelf = true) where T : Component
80  {
81  return component.transform.FindAncestorComponent<T>(includeSelf);
82  }
83 
91  public static T FindAncestorComponent<T>(this Transform startTransform, bool includeSelf = true) where T : Component
92  {
93  foreach (Transform transform in startTransform.EnumerateAncestors(includeSelf))
94  {
95  T component = transform.GetComponent<T>();
96  if (component != null)
97  {
98  return component;
99  }
100  }
101 
102  return null;
103  }
104 
111  public static IEnumerable<Transform> EnumerateAncestors(this Transform startTransform, bool includeSelf)
112  {
113  if (!includeSelf)
114  {
115  startTransform = startTransform.parent;
116  }
117 
118  for (Transform transform = startTransform; transform != null; transform = transform.parent)
119  {
120  yield return transform;
121  }
122  }
123 
130  public static void ForEachComponent<T>(this GameObject g, Action<T> action)
131  {
132  foreach (T i in g.GetComponents<T>())
133  {
134  action(i);
135  }
136  }
137  }
138 }
static void ApplyToHierarchy(this GameObject root, Action< GameObject > action)
Apply the specified delegate to all objects in the hierarchy under a specified game object...
static IEnumerable< Transform > EnumerateAncestors(this Transform startTransform, bool includeSelf)
Enumerates the ancestors of the specified transform.
Extensions methods for the Unity Component class. This also includes some component-related extension...