I want to code so that when I click on a GameObject, it changes colour with each click. For example, it starts off white: click to turn red, click again and it turns green, and so on and so forth until it get back to white.
I’ve got a single click working with Raycast. I’m guessing I’d need to do a string perhaps?
Hey there,
You don’t need a loop to loop through color’s. Use a variable to store current index of color and one to store the length of color array.
Color[] colors = new Color[] {Color.white, Color.red, Color.green, Color.blue};
private int currentColor,length;
// Use this for initialization
void Start ()
{
currentColor = 0; //White
length = colors.Length;
renderer.material.color = colors [currentColor];
}
In update, when ray hit’s increment the currentColor by 1. To make sure, it does not get above the max length, use the remainder operator.
void Update () {
if(Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
currentColor = (currentColor+1)%length;
renderer.material.color = colors[currentColor];
}
}
}
Change the script as per your code.
Cherno
2
You need to declare an array of colors to cycle through, first:
Color[] colors = new Color[] {Color.white, Color.red, Color.green, Color.blue};
Then, after the objects is hit by your RC, you call the following code:
Color goColor = yourObject.renderer.material.color;
for(int i = 0; i < colors.Length; i++) {
if(goColor == colors *&& i == colors.Length - 1) {*
yourObject.renderer.material.color = colors[0];
Return;
}
else {
yourObject.renderer.material.color = colors[i + 1];
Return;
}
}
There are probably better ways to do it but that should get you started.