- Home /
Instantiating multiple sprites and assigning different colors for each
I am trying to instantiate multiple circles sprites and then assigning each one a different color on it's Sprite Renderer, however, what I've got ends up assigning them all the same color, specifically the last color assigned, like it continues to update all of the circle's colors.
public GameObject circle;
public Transform spawnTransform;
public int numberOfCircles = 5;
public Color[] colors;
// Use this for initialization
void Start ()
{
GetAllColors ();
SpawnAllCircles ();
}
void GetAllColors()
{
colors [0] = Color.red;
colors [1] = new Color (255, 165, 0); //Orange
colors [2] = Color.green;
colors [3] = Color.blue;
colors [4] = Color.magenta;
}
void SpawnAllCircles()
{
for (int i = 0; i < numberOfCircles; i++)
{
GameObject newCircle = Instantiate (circle, spawnTransform);
newCircle.GetComponent<SpriteRenderer> ().sharedMaterial.SetColor ("_Color", colors [i]);
}
}
What I believe that should be happening is the for each of the five times the for loop is run, it'll create the newCircle GameObject, then change the color. I'd assume the variable would be deallocated from memory after each instance of the for loop, so I don't understand how this appears to be continuing to change the prior circle's colors.
Answer by MT369MT · Jul 29, 2018 at 07:02 PM
Hi, could you use:
newCircle.GetComponent<SpriteRenderer> ().color = colors[i];
instead using shared material?
Anyway new Color(255, 165, 0) will be yellow because Color goes from 0 to 1 so orange will be new Color(1, 0.647f, 0) or more easily you could use a Color32 that goes from 0 to 255.
Ah, that works. It's surprisingly simple, not sure how I didn't find that when I was trying to figure this out from the documentation.
Actually, the orange color, which looks like yellow in the inspector, ended up being red, and Color.green is black. I guess I'll have to look into this a bit more, now that I'm getting different colors. Thanks.
Now that I've come back to work out the colors the next day, there's not any problem with any of the colors. They just work as expected, with apparently no changes needed. I'll mark this as the answer, but if someone could explain to me why what I had originally asked about had not worked, I'd be very grateful. I just want to fully learn and understand from my mistakes, rather than just get an answer and move on. I feel as though it should've worked, but even now, I can't see what makes it wrong.
Your answer
Follow this Question
Related Questions
How to create shared color channels 1 Answer
Make the cube have the same color as the background every 3 seconds 0 Answers
How to change the color of an image every two seconds 1 Answer
How to change color of sprite as it moves over different backgrounds 2 Answers
How to change colors in turn? 1 Answer