- Home /
how to change object material with mouse click ?
hello,
I want to change the object material when click on object,i make this script in c# below but it change between two materials only and i want to change among three material as the third are not work,so what is the wrong with this
using UnityEngine;
using System.Collections;
public class oo : MonoBehaviour {
// put the first material here.
public Material logo;
// put the second material here.
public Material material2;
// put the third material here.
public Material material3;
bool FirstMaterial = true;
bool SecondndMaterial = false;
bool SecondndMaterial3 = false;
void Start ()
{
renderer.material = logo;
}
void OnMouseDown()
{
if (FirstMaterial)
{
renderer.material = material2;
SecondndMaterial = true;
FirstMaterial = false;
SecondndMaterial3 = false;
}
else if(SecondndMaterial)
{
renderer.material = logo;
FirstMaterial = true;
SecondndMaterial = false;
SecondndMaterial3 = false;
}
else if(SecondndMaterial3)
{
renderer.material =material3 ;
SecondndMaterial3 = true;
FirstMaterial = false;
SecondndMaterial = false;
}
}
}
Answer by mattssonon · Oct 02, 2013 at 05:59 PM
You never set SecondndMaterial3 to true. Change the second if conditional to this:
else if(SecondndMaterial)
{
renderer.material = logo;
FirstMaterial = false;
SecondndMaterial = false;
SecondndMaterial3 = true;
}
Answer by clunk47 · Oct 02, 2013 at 05:59 PM
I'd create a simple public array of materials, set the size and materials in the inspector. Then you'd want to use an int for the index, then simply cycle through on each click.
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
public Material[] materials;
int index = 0;
void Start()
{
renderer.material = materials[index];
}
void OnMouseDown()
{
index++;
if(index >= materials.Length)
index = 0;
renderer.material = materials[index];
}
}
Thank you! This worked for me, but I had to make sure a collider was on the affected objects. And for the newer Unity versions ($$anonymous$$e 2021), the wording is: GetComponent(less-than)Renderer(greater-than).material = materials[index];
*this forum page doesn't allow those less/greater-than symbols, its weird