How can a game object detect that it is being hit by a raycast?

When character controller is within 3 meters of a game object (lets say a cube) he has the option to press “space” to interact with said cube regardless if character controller is facing the cube or not. I’ve done that with a small trigger zone around intractable cubes and the trigger zone ignores raycast.

But I need interaction to function only when character controller is within 3 meters of the cube (inside cubes trigger zone) and are casting ray on/looking at the cube.

I tried adding function OnCollisionEnter(collision : Collision) or onCollisionStay to the object, but it does not seem to be triggable by raycast…

I kinda wish to avoid coding a complicated raycast if-else script on the character controller, especially when I have many intractable objects on the scene.

Any suggestions?

Use Vector3.Distance instead of a raycast. So attach something like this (pseudo-code) to your character controller :

var cube : Transform;

if (Vector3.Distance(transform.position, cube.position) <= 3) {
	if (Input.GetKeyDown(KeyCode.Space)) {
		//Do whatever you want to do here
	}
}	

Hope that helps, Klep

Thanks for the reply Kelp, this is certainly an interesting proposition. However, I need raycast, when character controller is looking at an object I display that’s object name on screen.

But what I really want to know, is there a way for the character controller to tell the object of interest to tell when it is being hit by raycast?

There is a way to tell an object when something collides with it, if only I had a function like “OnRaycastStay” or “OnRayCastHit”, or a different function that could detect when ray collides with an object, similar to how OnControllerColliderHit or OnTriggerStay behave.

For mine I used;

 if (Physics.Raycast (ray, hit, range))
    {    
        // we hit something      
        print ("I'm looking at " + hit.transform.name);
        Debug.DrawLine (ray.origin, hit.point);
    }

This one allows you to detect whether it’s hitting anyting.

But if that’s not what you want, then Kleps answer is perfect. :slight_smile: