Hey guys, quick question. I have a GameObject, “Tank”, with a rigidbody component. The Tank has children, grandchildren, great-grandchildren, and so-on. Children of every depth are dynamically created and removed during runtime. Some of these children are “Turrets”, which ‘kick’ when they fire. I need them to be able to access the rigidbody of the Tank regardless of their depth.
But here’s the kicker: “Tank” may also have a parent, so I can’t use ‘root.’ I also may have an arbitrary number of tanks, turrets, everything.
So, what I need is a way for an object to find a rigidbody in its ancestry. That is, search all of it’s parents (and their parents and so on) for a rigidbody to apply this ‘kick’ impulse to.
Any ideas? Perhaps a custom recursive function is in order, or is there an easier vanilla way?
(Using JavaScript please!) Thanks fellas!
Here’s my implementation - used as an extension on a game object:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
public static class GameObjectExtensions
{
public static T FirstAncestorOfType<T>(this GameObject gameObject) where T : Component
{
var t = gameObject.transform.parent;
T component = null;
while (t != null && (component = t.GetComponent<T>()) == null)
{
t = t.parent;
}
return component;
}
public static T LastAncestorOfType<T>(this GameObject gameObject) where T : Component
{
var t = gameObject.transform.parent;
T component = null;
while (t != null)
{
var c = t.gameObject.GetComponent<T>();
if (c != null)
{
component = c;
}
t = t.parent;
}
return component;
}
}
Usage from c#
var rbdy = gameObject.FirstAncestorOfType<RigidBody>();
From JS (the GameObjectExtensions class must be in Plugins/Standard Assets)
var rbdy = GameObjectExtensions.FirstAncestorOfType.<RigidBody>(gameObject);