- Home /
Using the object.Equals() method for a custom class
I've created my own class Contact to hold a bunch of variables on a series of gameobjects, and a series of the Contacts are being held in a list. I'd ideally like to be able to use the built in methods like list.Contains() for the sake of convenience. From what I've been able to find on the .Contains() method, it uses a method named Equals() in the class which has to be overridden.
I'm attempting to return true from .Equals() when the string "id" is the same for the compared Contacts. What I have so far is as follows:
public class Contact : object
{
public GameObject game_obj;
public string id;
public float level;
public float health;
public float distance = 0;
public Vector3 direction = new Vector3(0, 0, 0);
public bool more_stuff = false;
//constructors
public Contact(GameObject go)
{
game_obj = go;
id = go.name;
level = go.GetComponent<NpcManager>().level;
health = go.GetComponent<NpcManager>().health;
}
//comparator
public override bool Equals(Contact other)
{
Debug.Log("Called it.");
//check for null vals and compare types
if (other == null || GetType() != other.GetType())
{
return false;
}
return (id == other.id);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
The problem I'm having is that when I try to override the Equals method, unity throws an error saying that Contact.Equals(Contact) cannot override because object.Equals(object) is not a method.
The articles I've used: object.equals() and list.contains()
Answer by cjdev · Aug 20, 2015 at 07:56 PM
Check out this article. The problem is you need to override the System.Object Equals method and then implement your own Equals method for your object like this:
public override bool Equals(System.Object obj)
{
if (obj == null)
return false;
Contact c = obj as Contact ;
if ((System.Object)c == null)
return false;
return id == c.id;
}
public bool Equals(Contact c)
{
if ((object)c == null)
return false;
return c == c.id;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Why is Start() from my base class ignored in my sub-class? 4 Answers
Listing players by score 1 Answer
Getting NullReferenceException when creating class instance using List 1 Answer