Switching through colors with a script

Hello everyone,

sorry for the captions, my browser is crazy…

I wonder how I can select a cube in the game view and by clicking on it it changes the Color in a certain order.

The idea was like that:
Cube - clicked on - Color turns blue - clicked on - Color turns green - clicked on - Color turns red - clicked on, the circle repeates.

The Question now is how to do this. I thought that I may create an Array that stores different Colors. By clicking on the cube I then alter a Value or number, that descibes the Color in the Array and then I take this new Color and put it on the cube.

Now I am a very beginner to Unity and so far I have found no tutorial on how to store Colors/materials in Arrays and switch between them and putting them on gameObjects.

Do you have any idea on how to do this?

Thanks in Advance

Well, there are probably no more than one- or two-million ways to do this, so I’m not saying this is best (and, in fact, it contains a slight issue for production code, if you read the documentation on the material property of a Renderer), but this might be a start:

using UnityEngine;

public class ColorCycle : MonoBehaviour
{
    public Color[] colors;

    int color;
    Material material;

    void Start()
    {
        material = GetComponent<Renderer>().material;
    }

    private void OnMouseUpAsButton()
    {
        material.color = colors[color];

        color = color + 1;

        color = color % colors.Length;
    }
}

Thank you for the answer.

I currently getting headaches by trying to figure out how to use different arrays for my gameobjects, the materials and etc. I think I made a huge mess and every approach somehow makes other ideas obsolet…

My try now to create a gameObject with an optional color looks like that (code probably is totally wrong but that is something I have to focus on later):

//for creating the Material array
public Material[] color = new Material[9];
private int cc;

void Start()
{
cc = 5;
gameObject.renderer.material = color[cc];
}

And later I will try to use something like that:

void OnMouseDown()
{
if (0 < cc < 9)
{
cc = cc-1;
gameObject.renderer.material = color[cc];
}
else if (cc < 0 | cc > 9)
{
//Display some text "wrong move"
}

I will add some other code so I am able to increase the cc value as well so I can acces the full range of my Material[ ].

I understand that this now only works with the gameObject I am clicking on.
But can I somehow change other gameObjects in the scene as well?
Like change their cc value as well if I click on one gameObject. (Like a link from one gameObject to another?)