首页 > 解决方案 > 如何获得任何孩子的 prefan 父母,然后搜索特定的孩子?

问题描述

例如,这是 hierarhcy 中预制件的结构:

Prefab1
   Child1
   Child2
   Child3
     Child4
   Child5
     Child6
     Child7
   Child8

例如,我有一个附加到 Child3 或任何其他孩子的脚本,但假设 Child3,我想找到它的预制父级,然后获取并循环 Prefab1 的所有孩子并获取 Child6 和 Child7

现在 Child6 和 Child7 都标记为“ThisChilds”但是由于在层次结构中的世界中我有更多标记为“ThisChilds”的孩子,我想找到这个 Prefab1 的孩子 6 和 7,而不是世界上其他 Prefab 的孩子。

原因是我想在 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,我可以手动拖动它们,但这将是很多工作。

标签: c#unity3d

解决方案


在我看来,正确而干净的方法是根本不使用Find

而是在您的根对象上使用组件并通过您需要的检查器引用所有内容,例如

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);
    }
}

当然,您会使用一些更有意义的名称而不是Child3or child6;)


推荐阅读