Really Weird Color Results

I’m trying to Instantiate 10 bars across the screen. Each bar should have a random color of either green red blue or yellow. When I use this code though, why does the first bar end up as the color purple and all the other bars become the same color as each other. For instance the top bar will be pink and all the others below it will be blue. Any ideas?

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

public class Swiped : MonoBehaviour {

    public Vector3 spawnPos;
    public float spawnDelta = 1.5f;
    public int maxBars = 10;
    public GameObject bar;
    public int randInt;
    public Color randColor;
    Color[] barColors = {Color.red, Color.blue, Color.green, Color.yellow};

    void Start () {
        Init ();
    }
   
    void Update () {
   
    }
   
    void Init(){
        for(int i=0;i<maxBars;i++){
            Vector3 setPos = spawnPos;
            setPos.y -= i*spawnDelta;
            Instantiate (bar, setPos, Quaternion.identity);
            randInt = Mathf.RoundToInt (Random.Range (0f,barColors.Length-1));
            bar.GetComponent<MeshRenderer>().material.color = barColors[randInt];
        }
    }   
}

Looks like you’re instantiating a gameobject from a prefab called ‘bar’ but then trying to set the prefabs colour instead of the object you just created.

Try doing this:

GameObject NewBar = Instantiate(bar,setPos,Quaternion.identity) as GameObject;

then use

NewBar.GetComponent… rather than bar.GetComponent

1 Like

Dude thanks. People like you keep this community running by helping out the noobs like me.