From 18e345eb9b7caa6719ec65149715ce0a5a210fba Mon Sep 17 00:00:00 2001 From: Stephen Hodgson Date: Mon, 20 May 2019 16:12:30 -0700 Subject: [PATCH] Find common root for GameObject and Transforms (#197) --- .../Extensions/GameObjectExtensions.cs | 34 +++++++++++++++++++ .../Extensions/TransformExtensions.cs | 32 ++++++++++++++++- 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/XRTK-Core/Packages/com.xrtk.core/Extensions/GameObjectExtensions.cs b/XRTK-Core/Packages/com.xrtk.core/Extensions/GameObjectExtensions.cs index 0bc318523..713dddaf7 100644 --- a/XRTK-Core/Packages/com.xrtk.core/Extensions/GameObjectExtensions.cs +++ b/XRTK-Core/Packages/com.xrtk.core/Extensions/GameObjectExtensions.cs @@ -172,5 +172,39 @@ public static void SetRenderingActive(this GameObject gameObject, bool isActive, } } } + + /// + /// Given 2 GameObjects, return a common root GameObject (or null). + /// + /// GameObject to compare + /// GameObject to compare + public static GameObject FindCommonRoot(this GameObject g1, GameObject g2) + { + if (g1 == null || g2 == null) + { + return null; + } + + var t1 = g1.transform; + + while (t1 != null) + { + var t2 = g2.transform; + + while (t2 != null) + { + if (t1 == t2) + { + return t1.gameObject; + } + + t2 = t2.parent; + } + + t1 = t1.parent; + } + + return null; + } } } diff --git a/XRTK-Core/Packages/com.xrtk.core/Extensions/TransformExtensions.cs b/XRTK-Core/Packages/com.xrtk.core/Extensions/TransformExtensions.cs index 2ecdd51a9..7ad7598a7 100644 --- a/XRTK-Core/Packages/com.xrtk.core/Extensions/TransformExtensions.cs +++ b/XRTK-Core/Packages/com.xrtk.core/Extensions/TransformExtensions.cs @@ -96,7 +96,7 @@ private static IEnumerable EnumerateHierarchyCore(this Transform root /// Calculates the bounds of all the colliders attached to this GameObject and all it's children /// /// Transform of root GameObject the colliders are attached to - /// The total bounds of all colliders attached to this GameObject. + /// The total bounds of all colliders attached to this GameObject. /// If no colliders attached, returns a bounds of center and extents 0 public static Bounds GetColliderBounds(this Transform transform) { @@ -255,5 +255,35 @@ public static bool TryGetDepth(Transform target, Transform parent, ref int depth return false; } + + /// + /// Given 2 Transforms, return a common root Transform (or null). + /// + /// Transform to compare + /// Transform to compare + public static Transform FindCommonRoot(this Transform t1, Transform t2) + { + if (t1 == null || t2 == null) + { + return null; + } + + while (t1 != null) + { + while (t2 != null) + { + if (t1 == t2) + { + return t1; + } + + t2 = t2.parent; + } + + t1 = t1.parent; + } + + return null; + } } } \ No newline at end of file