- Home /
change object material on mouse click.
Hi all,
I would like to change the material of an object within a scene by clicking on it, I have some code which will change the material however it will run no matter where in the environment the mouse is clicked. I would like to restrict it so the script only runs if the mouse is clicked when over the object.
Thanks in advance for any advice!
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();
}
}
}
Answer by Julien-Lynge · Oct 05, 2011 at 04:04 PM
Physics.Raycast will return true if the ray hits anything - you then have to look at the RaycastHit to figure out what was actually hit.
What might work better for you is Collider.Raycast, which will look for collisions only with the collider specified. When that returns true you can be guaranteed you've actually clicked on the object.
Of course, that will ignore other objects so will still return true if your object is behind another object, and that may not be what you want, in which case you'll need to use the physics raycast and check hit.transform.name or something like
if (hit.transform == myTransform)
Good luck.
Answer by jigster · Oct 07, 2011 at 03:43 PM
Thank you for the response, it proved a great help, however I have another issue. My script works perfectly well when I create a scene from scratch and apply it to an object, however when I try to use the code in an existing scene by adding it to an object it doesn't work. I get no errors and the script simply does not run. The code is below:
var myMaterials : Material[]; var NextMaterial : int = 0; function NextMaterialUsed() { renderer.sharedMaterial = myMaterials[NextMaterial]; if(NextMaterial < myMaterials.length-1) NextMaterial += 1; else NextMaterial = 0; }
function Update () { if ( Input.GetButtonDown("Fire1") ) { var hit : RaycastHit; var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition); if (Physics.Raycast (ray, hit, 100.0)) if(hit.collider.gameObject.name == "object name") { NextMaterialUsed(); } } }