how can I get my prefab to have a different material on instantiation

Im stuck on how i can get my game object prefab to have a randomly selected material out of three different ones on each instantiation. This is the code i have:

void Start ()
    {
        rend = GetComponent<Renderer>();
        mInital = rend.material;
        myTransform = transform;

        colourSelect = Random.Range(0, 3);
        switch (colourSelect)
        {
            case 1:
                mInital = mRed;
                break;
            case 2:
                mInital = mBlue;
                break;
            case 3:
                mInital = mYellow;
                break;
        }

I would appreciate it if anyone could help. Im just trying to teach myself everything about Unity :slight_smile:

I guess it should end with rend.material.color = mInitial; But also, keep in mind that Random.Range(0, 3) can return values 0, 1 or 2. Not 1, 2 or 3. Your code will wither keep the original color or use red/blue but never yellow.

You could also make it a little easier to change:

public Color[] colors = { Color.red, Color.blue, Color.yellow };

void Start()
{
    var renderer = GetComponent<Renderer>();
    if (colors.Length > 0)
        renderer.material.color = colors[Random.Range(0, colors.Length)];
}

Now you don’t have to limit yourself to 3 colors.