例如,这是层次结构中的预制结构:
Prefab1
Child1
Child2
Child3
Child4
Child5
Child6
Child7
Child8
例如,我有一个脚本附加到Child3或任何其他孩子上,但是假设Child3,我想找到它的预制父对象,然后遍历Prefab1的所有孩子,并获得Child6和Child7
现在,Child6和Child7都标记为“ ThisChilds” 但是,由于在世界的层次结构中,我将更多的孩子标记为“ ThisChilds”,因此我想查找此Prefab1的孩子6和7,而不是世界上其他Prefabs的孩子。
原因是我想在附属于Child3的脚本中分配Child6和Child7
例如,Child3中的脚本为:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class GetChilds : MonoBehaviour
{
public GameObject Child6
public GameObject Child7
但是我不是想在编辑器中拖动此Childs手册,而是要自动找到它们,并在Start()中将它们分配给Child6和Child7,我可以将它们拖动为手册,但这将需要很多工作。
答案 0 :(得分:0)
如果要查找Prefab1,并且其根游戏对象位于层次结构中,则可以像
一样找到它Gameobject rootGameobject = child3.transform.root.gameobject;
,然后,如果您想找到该游戏对象的任何子代,则可以使用
Gameobject Child6 = rootGameobject.transform.Find("Child6");
Gameobject Child7 = rootGameobject.transform.Find("Child7");
即使您可以找到像这样的嵌套子代
Gameobject Child67 = rootGameobject.transform.Find("Child6/Child67");
答案 1 :(得分:0)
在我眼中,正确而整洁的方式是完全不使用Find
。
相反,您可以在根对象上使用Component并通过所需的Inspector引用所有内容,例如
public class YourController : MonoBehaviour
{
[SerializeField] private GameObject child3;
[SerializeField] private GameObject child6;
// etc whatever you need
public GameObject Child3 => child3;
public GameObject Child6 => child6;
}
然后在您的子组件中执行
public class Child3Component : MonoBehaviour
{
// Best if you reference this already in the Inspector
[SerializeField] private YourController yourController;
private void Awake()
{
// As fallback get in once on runtime
if(!yourController) yourController = GetComponentInParent<YourController>();
}
private void SomeMethod()
{
// Now access the references you need
Debug.Log(yourController.Child6.name);
}
}
当然,您将使用一些更有意义的名称来代替Child3
或child6
;)