c# - 如何获得任何孩子的 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,我可以手动拖动它们,但这将是很多工作。
解决方案
在我看来,正确而干净的方法是根本不使用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);
}
}
当然,您会使用一些更有意义的名称而不是Child3
or child6
;)
推荐阅读
- ruby-on-rails - form_for 助手给了我一个错误,尽管它在那里
- libgdx - 粒子发射器的数量会影响性能吗?
- python-2.7 - 安装 tensorflow 时出现“没有名为队列的模块”
- identityserver4 - IdentityServer4 - 有没有办法在授权代码流中静默地对用户进行身份验证?
- java - Java 等到使用 Selenium 加载页面
- python - 如果我在 matplotlib 中有图形(或轴)列表,如何创建多个图?
- azure - Microsoft Azure 流分析和 Blob 存储输入
- c++ - 从 Arduino SD 卡模块到 Array 的文件名
- python - Python 脚本“独立”
- java - Runge-Kutta 4 阶与 2 阶 ODE 错误