Why are these objects always equal using ==? (Solved)

I recently followed a pathfinding tutorial and ran into a strange problem that only I seem to be having. There is a class called PathNode which stores x and y values and I create a grid of these pathnodes for the pathfininding. The A* pathfinding algorithm is unable to perform its logic since no matter what I do, unity always sees all PathNodes as being equal to all other PathNodes. If I create a simple test script to create some pathnodes and check their equallity with ==, Unity always says they are equal. The most confusing part of this is I cant find a solution to this because it seems like I am the only one dealing with this issue. What’s happening here?

public class PathNode : MonoBehaviour
{
    public int x;
    public int y;

public PathNode(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
private void Start()
    {
        PathNode pathnode1 = new PathNode(0, 0);
        PathNode pathnode2 = new PathNode(1, 1);

        if(pathnode1 == pathnode2)
        {
            Debug.Log("pathnodes are equal");
        }
    }

Unable to replicate, which version of unity is it?

2020.1.3

I suggest to check hashCode of these two objects. It appears, they will be equal.

Just guessing but you do not instance the monobehavioirs correctly and there for the equals overload does not work as it should

1 Like

I think you might have just hit the nail on the head. I don’t think these need to inherit monobehavioir. I feel like a dope! Thank you.

1 Like

I think that you should either implement your own Equal method or compare x and y values directly instead of comparing two class instances.
You also could implement the IEquatable interface on your class.

https://stackoverflow.com/questions/8400028/comparing-two-instances-of-a-class

Since pathnode1 and pathnode2 are two different instance of the PathNode class, pathnode1 will never be equal to pathnode2 even if x and y values are equals.

You could add a method like static bool Equal(PathNode first, PathNode second) and adding the x and y comparaison inside.

Thanks for the info. It turns out it was actually the monobehavior as MDADigital pointed out but I will read up on the source you provided since I am now curious about the subject.