Not able to Remove Vector2 element from SortedSet in C# script in Unity.

I have declared a sorted set like this -

class ComparerForClassAByOrder : IComparer<Vector2> {
    public int Compare(Vector2 left, Vector2 right) {
		if(left.x==right.x)
			return (int)Mathf.Sign((int)(left.y-right.y));
        return (int)Mathf.Sign((int)(left.x-right.x));
    }
}


SortedSet<Vector2> open = new SortedSet<Vector2>(new ComparerForAByOrder());

Now When I am trying to remove an element from it, it is not getting removed. I am doing this -

		open.Add(new Vector2(0,0));
		bool done = open.Remove(new Vector2(0,0));
		Debug.Log(done);

And the result is False. I don’t know what is going wrong. Please suggest me a method to remove a Vector2 element from SortedSet.

Because your comparer does never return “equal” (i.e. a value of 0). Mathf.Sign will always return either 1 or -1. If you pass 0 it will return 1. However equality will require your compare method to return 0.

You should do something like this:

public int Compare(Vector2 left, Vector2 right) {
    var dif = left - right;
    if(dif.x == 0 && dif.y == 0)
         return 0;
    else if(dif.x == 0)
         return (int)Mathf.Sign(dif.y);
    return (int)Mathf.Sign(dif.x);
}