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.
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;
}
}