Get collider from raycast

Hello!

I am trying cast a ray that once it hits a gameobject within less than 100 range it will return the gameobject…

This is what I got:

var hit : RaycastHit;

function FixedUpdate () {

if (Physics.Raycast (transform.position, Vector3(-1, 0, -1), 100)) {
    print ("There is something in front of the object! y-");
    Debug.Log(hit.collider.gameObject.name);
        }      
}

Does anyone can help me?

4 Answers

4

Just in case this is useful to someone,

to get the GameObject associated with the collider struck by the raycast, simply :

GameObject g = hit.collider.gameObject;
string name = g.name;

Thank you!

From the manual:

// Raycast up to 100 meters down

function Update () {
    var hit : RaycastHit;
    if (Physics.Raycast (transform.position, -Vector3.up, hit, 100.0)) {
        var distanceToGround = hit.distance;
    }
}

The variable ‘hit’ contains a reference to the collider.

Sorry, but thats not what I want…

What I want is that when the ray cast collides with a gameobject it must return the gameobject name…

var colliderName = hit.collider.gameObject.name;