Unity NPC漫游系统:如何从其他游戏对象获取子物体Transform?
Unity NPC漫游系统:获取父物体下子物体Transform的解决方案
先修正代码中的索引越界问题
你当前代码里的Random.Range(0, destinationCount + 1)会导致索引越界——子物体的索引范围是0到destinationCount - 1,所以应该改成:
chosenDestination = Random.Range(0, destinationCount);
获取子物体Transform的几种方法
方法1:直接通过索引获取Transform
使用Transform.GetChild()方法,传入随机选中的索引即可直接拿到子物体的Transform:
destinatonTransform = destinationParent.transform.GetChild(chosenDestination);
方法2:先获取子物体GameObject再取Transform
如果需要先拿到子物体的GameObject对象,再获取其Transform,可以这么写:
destination = destinationParent.transform.GetChild(chosenDestination).gameObject; destinatonTransform = destination.transform;
优化方案:提前缓存所有目标点Transform
如果后续需要频繁切换目标点,建议在Start阶段就把所有子物体的Transform缓存到List中,避免重复调用GetChild带来的性能开销:
using System.Collections; using System.Collections.Generic; using UnityEngine; // 移除无用的UnityEngine.Apple命名空间 public class PersonBehaviour : MonoBehaviour { public GameObject destinationParent; private int chosenDestination; private GameObject destination; private int destinationCount; private Transform destinatonTransform; private List<Transform> allDestinationTransforms = new List<Transform>(); void Start() { destinationParent = GameObject.Find("Destinations"); // 遍历父物体下所有子物体,缓存Transform foreach (Transform child in destinationParent.transform) { allDestinationTransforms.Add(child); } destinationCount = allDestinationTransforms.Count; chosenDestination = Random.Range(0, destinationCount); destinatonTransform = allDestinationTransforms[chosenDestination]; } }
内容的提问来源于stack exchange,提问作者Mr Glub
相关产品推荐
相关产品推荐

