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..
Answer by · Sep 23, 2010 at 10:16 AM
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.
How about this Camera Ray Casting in C# code ... I tried to convert it to C# but there has the problem with passing hit...
In C# you need to add "out" before hit. i.e. if ( Physics.Raycast( ray, out hit, 100.0f ) )
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 On$$anonymous$$ouseExit().
Your answer