我正在用unity制作一款主要由UI组成的游戏。UI是由许多在层次结构中带有按钮的父游戏对象组成的。我需要得到父母的名字(一个空的游戏对象),当点击按钮。到目前为止,我已经试过了:
CountryText.text = transform.parent.name;
但它没有起作用。有什么我能做的吗?
假设您不是在谈论父对象,因为transform.parent
可能是答案,而是层次结构中的祖先之一,那么一个好的方法是使用gameObject.tag
标记特定对象并遍历层次结构。您可以在检查器中分配标签,并通过调用
public Transform FindParentWithTag(Transform child, string tag)
{
Transform next = child;
while (next.parent != null)
{
if (next.parent.tag == tag)
{
return next.parent;//found ancestor with tag
}
next = next.parent.transform;
}
//search failed
return null;
}