Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. We are looking for feedback on the experimental Unity Safe Mode which is aiming to help you resolve compilation errors faster during project startup.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

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:
    13
    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:
    13
    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
unityunity