Change color [newbie question]

Hi!
I want to change color of my object every touch. Base colors are (red, blue, yellow, green). Color is changing every touch to next color (red->blue ->yellow->green and after green (if touched) back to red.
I was looking since 2 days for any tips in google but I found only helps with “OnMouseDown” or “key” answers.
(the code is not finished)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test : MonoBehaviour {

// Use this for initialization
void Update()
{
for (int a = 0; a < 4; ++a) {
int fingerCount = 0;
foreach (Touch touch in Input.touches)
{
if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
fingerCount++;

}
GetComponent().color = Color.red;
if (fingerCount == 1)
{
GetComponent().color = Color.blue;

}
if (fingerCount == 2)
{
GetComponent().color = Color.yellow;

}
if (fingerCount == 3)
{
GetComponent().color = Color.green;
}
}
}
}

OnMouseDown will work with touches. I only use touches if I need specific touch events like drag/lift etc. Also, you are using a for loop unnecessarily. You are basically calling the same code 4 times in 1 frame which is putting your color back where it started.

1 Like

I would have a toggle function like:

Color[] _colors = {Color.green, Color.blue}; // etc.
int _currentColorIndex = 0;
private Color GetNextColor()
{
     return _colors[++_currentColorIndex % _colors.Length];
}

Then OnMouseClick call the function similar to this.

1 Like

Thanks a lot!