c# - 如何在不意外更改引用的情况下通过引用添加到队列?

标签 c# unity3d

我有一系列属于类的路标。它们继承单声道行为,因此它们不能是结构,而且它们的行为取决于路径点的派生类型。

我将 AI 访问的每个航路点都添加到队列中,这样它们就不会回到之前访问过的航路点。

但是,如果我现在将 AI 的 CurrentWaypoint 更改为他到达的下一个,这将更改队列中的那个。所以我最终得到了一个包含所有相同航点引用的队列。

我怎样才能防止这种情况,但仍然能够通过引用检查检查队列中是否存在 CurrentWaypoint?我相信如果我只使用一个副本,那么引用检查将失败,所以这也不好。

我的两个方法是:

private bool HasVisited(Waypoint wp)
{
    if (_previousVisits.Contains(wp))
    {
        return true;
    }

    return false;
}

private void AddVisited(Waypoint wp)
{
    // we only need the last 2 wp's visited
    if (_previousConnections.Count > 1)
    {
        _previousConnections.Dequeue();
    }
    _previousVisits.Enqueue(wp);
}

这个问题的最佳解决方案是什么?

最佳答案

为此,我将围绕 Waypoint 构建一个包装类以提供我自己的比较,例如:

public class WaypointWrapper
{
    private readonly Vector3D _waypointPosition;

    public WaypointWrapper(Waypoint waypoint)
    {
          /* Assuming the Waypoint class has a position property that is a Vector3D struct */
          _waypointPosition = waypoint.position;
    }

    public override Equals(object obj)
    {
         var otherWaypointWrapper  = obj as WaypointWrapper;

         if(otherWaypointWrapper == null)
             return false;

         return otherWaypointWrapper._waypointPosition.Equals(_waypointPosition);
    }

    public override int GetHashCode()
    {
         return _waypointPosition.GetHashCode();
    }
}

关于c# - 如何在不意外更改引用的情况下通过引用添加到队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50052482/

相关文章:

c# - 使用 Entity Framework 6.1 IndexAttribute 属性声明字符串字段键时指定最大长度?

c# - 从字符串获取枚举类型

c# - GetComponent 从 4 升级到 5 不起作用

c# - 如果未发送任何内容,验证将不起作用?

c# - 使用 foreach 同时遍历多个列表(语法糖)

c# - toString保留小数位

macos - 启用 Developer Tools Access 会导致 Unity 和 Activity Monitor 崩溃

c# - Unity Player 正在向自己射击

c# - Unity3d MeshRender

c# - 如何等待场景卸载?