- Home /
[Duplicated Question] Change Object material on mouse click
Question already posted at http://answers.unity3d.com/questions/173658/change-object-material-on-mouse-click.html
Hi all,
In a game I am currently building I would like players to click on models within the environment to change the material used on that object. For example, a player can click on the curtains to cycle through a range of designs.
I have a script which works, but I would like each object in a scene to act independently, currently if the script is attached to more than one object, all will change when the mouse is clicked.
I would like it so the script recognises which object I am clicking on and only changes the material on that model, I have mesh colliders on all of the models.
Code:
var myMaterials : Material[]; var NextMaterial : int = 0;
function NextMaterialUsed() { renderer.material = myMaterials[NextMaterial]; if(NextMaterial < myMaterials.length-1) NextMaterial += 1; else NextMaterial = 0; }
function Update () { if (Input.GetButtonDown ("Fire1")) {
var ray :Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit: RaycastHit;
if (Physics.Raycast (ray, hit, 100.0))
{
// Changes texture if hit
NextMaterialUsed();
}
}
}