Unity3D 查找该子物体具有某个组件的最近的父物体
如下,查找gameObject(当前物体)具有Image组件的最近的父物体,并输出.
void Start ()
{
//查找gameObject(当前物体)具有Image组件的最近的父物体,并输出
var v = FindInParent<Image>(gameObject);
if (v != null)
print(v.name);
else
print("不存在有该控件的父物体!");
}
static public T FindInParent<T>(GameObject g) where T : Component
{
if (g == null) return null;
var comp = g.transform.parent.GetComponent<T>();
if (comp != null) return comp;
var t = g.transform.parent.parent;
while(t!=null && comp == null)
{
comp = t.gameObject.GetComponent<T>();
t = t.parent;
}
return comp;
}