Do something when mouse cursor "hits / looks at" object

Hi,

At the moment I have a simple crosshair in the center of the screen. This functions as the mouse pointer and always stays in the center of the screen.

In my scene there are a few boxes placed with the tag “box”. What I want is that a “Debug.Log” text is shown once my mouse goes over this object. So basically when I move the crosshair onto the object, a text has to be shown in the console. How do I find out if the cursor “aims” at the object? I am using javascript and a First Person Controller. This may ONLY work on objects with the tag “box”.

function OnMouseEnter() can be used here, it is called when the mouse hovers over a gameobject or texture (more precisely a Collider or GUI element).

Here’s a demonstration

function OnMouseEnter()
{

Raycast from the position of the cursor, check the name or tag of the collider returned from the raycast, if so then DoStuff();

var rayMousePos = Camera.main.ScreenPointToRay(Input.mousePosition);
var rayHit : RaycastHit;

if ( Physics.Raycast(rayMousePos, rayHit) )
{
	 Debug.DrawLine( rayMousePos.origin, rayHit.point );
	
	 Debug.Log( " Ray Hit Name : " + rayHit.collider.gameObject.name );
	 Debug.Log( " Ray Hit  Tag : " + rayHit.collider.gameObject.tag );
}