Search Unity

Not understanding the class RayHitComparer in the ThirdPersonCharacter script

Discussion in 'Scripting' started by Tomas_Kok, Jun 9, 2015.

  1. Tomas_Kok

    Tomas_Kok

    Joined:
    Oct 5, 2014
    Posts:
    12
    Hey.

    I am trying to understand the class RayHitComparer in the ThirdPersonCharacter script in the standard assets (I want to convert it to JS).

    Code (CSharp):
    1. private class RayHitComparer : IComparer
    2.         {
    3.             public int Compare(object x, object y)
    4.             {
    5.                 return ((RaycastHit) x).distance.CompareTo(((RaycastHit) y).distance);
    6.             }
    7.         }
    The first problem is the type object of x and y. According to Unity, it is not a valid type (in JS).
    The second problem is ((RaycastHit)x). What is happening here? How can x be next to RaycastHit without something like a "." or "*"?

    I understand what this class is supposed to do, but I do not understand how it is doing it. Does anybody know?
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    (type) variable

    is "casting" the "variable" to the "type"

    Code (csharp):
    1.  
    2. float x; // declare variable x as a float
    3. x = 1.23; //initialise the float to a value
    4. // change the type to int and send it to the console
    5. Debug.Log((int) x); // 1
    6.  

    I think you could just use the untyped "var" in place of object. Using "object" (base class of everything) is pretty much saying "will accept any type of thing as a parameter"
     
  3. Tomas_Kok

    Tomas_Kok

    Joined:
    Oct 5, 2014
    Posts:
    12
    Thank's! I totally forgot about casting.
    And the object type in C# now makes sense, because you always have to define your variables and there is no "var" like in JS
     
  4. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148