Raycast Collision

Hello,

I want to use a 2 units long Raycast which is fixed to the player’s eye to “sense” the useable prefabs. How can I get the name of the gameobject which is collided by the raycast?

I used this sample code on the eye joint:

#pragma strict
function FixedUpdate() {
var fwd: Vector3 = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, 2))
print(“There is something in front of the object!”);
}

The OnTriggerEnter ( col: Collider ) doesn’t work.

Certain flavors of Physics.Raycast can return a RaycastHit structure.

Inside that RaycastHit structure is a reference to the collider it hit, and that has the .name property on it.

In Unity2D I use a function like this. Don’t quote me for good code, but it’s something to look at. Layer 10 is the layer the objects are on that I’m testing against. If it returns false my sprite can’t travel in that direction. I test against the tags of items being hit.

public bool raycast_travel(Vector2 travelDirection)
    {

        // create layer mask for objects
        int layerMask = 1 << 10;

        RaycastHit2D hit = Physics2D.Raycast(transform.position, travelDirection, 1.0f, layerMask);

        if (hit.collider != null) {
                       
            switch(hit.collider.gameObject.tag)
                {
                    case "wall":
                        return false;
                    break;
                    case "floor_item":
                        return false;
                    break;
                    default:
                        return true;
                    break;

                }

        } else {

            return true;

        }

    }

Thank you guys, I found a working solution:

private var hit : RaycastHit;
function Update ()
     {

        if(Physics.Raycast( Camera.main.ScreenPointToRay(Input.mousePosition), hit, 2.0f ))
        {
            transform.root.GetComponent(Player_Main).CollidedByUse = hit.transform.gameObject;
        }
        else
            transform.root.GetComponent(Player_Main).CollidedByUse = null;
    }

But what if 2 or more gameobjects colliding with RayCast? How is it possible to use only the closest?