如何通过引用添加到队列而不意外更改引用?



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

我将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();
}
}

最新更新