Search code examples
c#unity-game-engineunityscript

Raycast - convert from C# to UnityScript


I was following a tutorial for Unity3D that was written in C# and was attempting to do it in UnityScript. The following line is the only one that I couldn't convert correctly and it has to do with Raycasting.

Here's the C# from the tut.

if(Physics.Raycast(ray, out hit, Mathf.Abs(deltaY), collisionMask)){
    ....
}

Here are my relevant variables that I have.

var ray : Ray;
var hit : RaycastHit;
var collisionMask : LayerMask;
var deltaY : float = moveAmount.y; // moveAmount is a Vector2

Here is the signature for Physics.Raycast

function Raycast (origin : Vector3,
                  direction : Vector3,
                  distance : float = Mathf.Infinity,
                  layerMask : int = kDefaultRaycastLayers) : boolean

I know that my problem is that using UnityScript doesn't recognize what 'out' is and I don't know what to substitute in its place.


Solution

  • According to the documentation:

    static function Raycast(ray: Ray,
                            hitInfo: RaycastHit,
                            distance: float = Mathf.Infinity,
                            layerMask: int = DefaultRaycastLayers): bool;
    

    Parameters (read the description for hitInfo)

    ray          The starting point and direction of the ray.
    distance     The length of the ray.
    hitInfo      If true is returned, hitInfo will contain more information about where the 
                 collider was hit (See Also: RaycastHit).
    layerMask    A Layer mask that is used to selectively ignore colliders when casting a ray.
    

    In C#, out passes by reference, which allows the function to modify the value outside its scope. In UnityScript, you don't need to define when to pass by reference or value. So, you simply omit the out.

    var ray : Ray;
    var hit : RaycastHit;
    var collisionMask : LayerMask;
    var deltaY : float = moveAmount.y; // moveAmount is a Vector2
    
    if (Physics.Raycast(ray, hit, deltaY, collisionMask)) {
        //hit will contain more information about whether the collider was a hit here.
    }
    

    Notice, according to the LayerMask documentation, LayerMask can be implicitly converted from an integer.