change the colour of the object when mouse is over the object

How can I change the material of the object if there is a mouse placed over that 3D object. I've seen the dragObject script but I don't want to use RigidBody although I am just going to use simple collider for that..

1 Answer

1

An easy solution would be to use OnMouseOver. Example code to set to red when mouse is over:

var initialColor : Color;

function Start()
{
   initialColor = renderer.material.color;
}

function OnMouseOver()
{
   renderer.material.color = Color.red;
}

function OnMouseExit()
{
   renderer.material.color = initialColor;
}

Alternatively, you could raycast from the camera position to the mouse position. The benefit of the Raycast is that you can specify a layerMask (to only hit objects on a given layer).

function Update()
{
   var hit : RaycastHit;
   var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
   if ( Physics.Raycast( ray, hit, 100 ) )
   {
      if ( hit.collider.gameObject.renderer )
         hit.collider.gameObject.renderer.material.color = Color.red;
   }
}

In these examples, the color of the renderer material is explicitly set to red when the mouse is over it, but you can change it according to your needs.

Any idea on how to detect when raycast is no more hitting the same object? I was able to change color on "selection", each update while raycast is hitting the object the color is changed to the new one, but I'm looking in a efficient way to "restore" the initial color of the object like the OnMouseExit().