Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Checking if two Generic object are the same

Discussion in 'Scripting' started by RoughSpaghetti3211, Apr 16, 2018.

  1. RoughSpaghetti3211

    RoughSpaghetti3211

    Joined:
    Aug 11, 2015
    Posts:
    1,695
    Hello,

    I have a generic class with type U, how can I check if two object are the same.

    Code (csharp):
    1.  
    2.     public abstract class AStarFindPath<T,U> : MonoBehaviour
    3.         where U : IAStarPathFinding<U>
    4.     {
    5.             // both are of type U
    6.             U startNode = GetNodeFromWorldPoint (startPos);
    7.             U targetNode = GetNodeFromWorldPoint (targetPos)
    8.             //error CS0019: Operator `==' cannot be applied to operands of type `U' and `U'
    9.             if ( currentNode == targetNode ) {
    10.                         //sw.Stop();
    11.                         //print ("Path found: " + sw.ElapsedMilliseconds + " ms");
    12.                         _pathSuccess = true;
    13.                         break;
    14.                     }
    15.  
    16.     }
    17.  
     
  2. kru

    kru

    Joined:
    Jan 19, 2013
    Posts:
    452
    All C# objects have the Equals() method. This is what you can use to test if two objects are equals.

    However, what does it mean for two objects to be equal? That is a question with no easy answer. By default, the Equals() method will return true if two reference type objects share the same reference, or if two value type objects have identical field values. It is up to you to define more complex behavior for your custom classes by overriding the Equals() method in your class definition.
     
  3. RoughSpaghetti3211

    RoughSpaghetti3211

    Joined:
    Aug 11, 2015
    Posts:
    1,695
    Perfect, thanks for the reply, I think since both are ref type and cant share a mem address the default should work just fine.