首页 > 解决方案 > How to add to a queue via references without changing references accidently?

问题描述

I have a series of way points that are classes. They inherit mono behaviours so they cannot be structs, plus they have behaviours depending on the derived type of way point.

I add each waypoint an AI visits to the queue so they don't wander back to a previous visited one.

How ever, if i now change the AI's CurrentWaypoint to the next one he arrives at, this changes the one in the queue. So i end up with a queue of all the same waypoint reference.

How can i prevent this but still be able to check if CurrentWaypoint exists in the queue via reference checks ? I believe if i just use a copy then the reference checks will fail so thats not good either.

My two methods are:

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);
}

Whats the best solution to this problem ?

标签: c#unity3d

解决方案


To do so, I would build a wrapper class around Waypoint to provide my own comparison such as:

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

推荐阅读