Unity 社区您好,
我目前在 Unity 中遇到 AICarScript 的问题,特别是
path
数组为空。我已经实现了一个路点跟踪系统,其中汽车应遵循检查器中指定 pathGroup
下的子对象定义的路径。
但是,当我运行脚本时,遇到以下错误消息:
我仔细检查了以下几个方面:
检查器分配:我已将检查器中的
pathGroup
变量正确分配给包含航点的游戏对象。
子对象: 航路点确实是分配给
pathGroup
的游戏对象的子对象。
层次结构: 航点按正确的层次结构排列,没有额外不必要的父子关系。
我已将调试日志添加到
GetPath
方法中,以打印 path
数组的长度和子对象的名称。奇怪的是,数组长度为 0,尽管我希望它更大。
// GetPath method
void GetPath()
{
Transform[] pathObjs = pathGroup.GetComponentsInChildren<Transform>();
path = new Transform[pathObjs.Length - 1];
for (int i = 1; i < pathObjs.Length; i++)
{
if (pathObjs[i] != pathGroup)
{
path[i - 1] = pathObjs[i];
}
}
Debug.Log("Path Length: " + path.Length);
for (int i = 0; i < path.Length; i++)
{
Debug.Log("Waypoint " + i + ": " + path[i].name);
}
if (path.Length == 0)
{
Debug.LogError("Path array is empty. Make sure to assign a valid path in the inspector.");
}
}
I'm seeking guidance on what might be causing the path array to remain empty during runtime. Has anyone encountered a similar issue, or can someone offer insights into potential pitfalls related to this scenario?
Thank you for your time and assistance guys.
我在这里看到的唯一原因:pathObjs.length 等于 1。我建议您通过添加额外的日志消息来检查它:
Transform[] pathObjs = pathGroup.GetComponentsInChildren<Transform>();
Debug.Log($"child count: {pathObjs.Length}");
尝试一下并确保它是真的。
也许航路点对象被禁用?您也可以使用它来获取禁用的对象。
pathGroup.GetComponentsInChildren<Transform>(true);