C# - Unity 因此代码而崩溃 - 基于 GameObject 标记创建变换数组

C# - Unity crashes with this code - creating Transform array based on GameObject tag

我在 3D 环境中工作,这是一栋有 16 个房间的房子。在每个房间里,我都放置了一个带有标签 "RoomsToScanTag" 的隐形立方体。我正在使用一个名为 Behavior Designer 的资产,在我的检查器中我已经给出了要查找的标记名(在本例中为 "RoomsToScanTag")。有了这个标记名,我希望机器人先去 room1,然后继续去 room2,直到 room16。

这是我的代码

using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;

public class MoveTowardsNew : Action
{
    private Transform[] roomsToScanHAHA;
    public string targetTagRooms;
    public Transform targetyo;
    int i = 0;
    int controlNumber = 0;

    public override void OnAwake()
    {
        var targets = GameObject.FindGameObjectsWithTag (targetTagRooms);
        roomsToScanHAHA = new Transform[targets.Length];
        for (int i = 0; i < targets.Length; i++) {
            roomsToScanHAHA [i] = targets [i].transform;
        }
    }

    public override TaskStatus OnUpdate()
    {
        while (controlNumber < roomsToScanHAHA.Length)
        {
            targetyo = roomsToScanHAHA [controlNumber];
            if (Vector3.SqrMagnitude (transform.position - targetyo.position) < 0.5f)
            {
                if (controlNumber < roomsToScanHAHA.Length) {
                    controlNumber++;
                }
                return TaskStatus.Success;
            }
        }
        NavMeshAgent agent = GetComponent<NavMeshAgent> ();
        agent.destination = targetyo.position;
        return TaskStatus.Running;
    }
}

我的问题

Unity崩溃了...和这段代码有关,我想不通。有人知道出了什么问题吗?

这是我正在处理的图片:

提前致谢!

像往常一样,while loop 没有终止:

    while (controlNumber < roomsToScanHAHA.Length)
    {
        targetyo = roomsToScanHAHA [controlNumber];
        if (Vector3.SqrMagnitude (transform.position - targetyo.position) < 0.5f)
        {
            if (controlNumber < roomsToScanHAHA.Length) {
                controlNumber++;
            }
            return TaskStatus.Success;
        }
    }

第一个运行:controlNumber = 0;

假设数组 roomsToScanHAHA 中的第一个元素不符合条件:(Vector3.SqrMagnitude (transform.position - targetyo.position) < 0.5f)controlNumber 不会增加并且会继续检查第一个元素的条件。这导致无限循环。

因此您可以将代码更改为如下内容:

    while (controlNumber < roomsToScanHAHA.Length)
    {
        targetyo = roomsToScanHAHA [controlNumber];
        if (Vector3.SqrMagnitude (transform.position - targetyo.position) < 0.5f)
        {
            return TaskStatus.Success;
        }
        controlNumber++;
    }

希望对您有所帮助