unity – How can I color each squad in another color?


First I would rename the method ColorSquads to ColorSquad. After all, it changes the color of one squad, not of multiple. Then I would add a second parameter color so it takes the color which it is supposed to use for this particular squad:

private void ColorSquad(GameObject squad, Color color)
{
    Renderer rend = squad.GetComponent<Renderer>();
    rend.material.SetColor("_Color", color);
}

But now you of course need to state which color you want to use for each squad within the for-loop. And considering that your code allows any number of squads, you need to decide here which squad-number should get which color. A simple way to do that is via a switch/case:

switch(i) {
   case 0: ColorSquad(newSquad, Color.green); break;
   case 1: ColorSquad(newSquad, Color.red); break;
   case 2: ColorSquad(newSquad, Color.blue); break;
   case 3: ColorSquad(newSquad, Color.yellow); break;
   case 4: ColorSquad(newSquad, Color.cyan); break;
   case 5: ColorSquad(newSquad, Color.magenta); break;
   default: ColorSquad(newSquad, Color.white); break;
}

This will color the first 6 squads with 6 different colors and then use white for any further squads. If you want to support more squads with more colors, then modify this code accordingly.

Another option would be to make those colors configurable in the inspector of this component. Add this variable to the class:

public Color[] squadColors;

Then in the for-loop:

if (i < squadColors.Length) {
    // pick the color from the list
    ColorSquad(newSquad, squadColors[i]);
} else {
    // default color when you run out of colors
    ColorSquad(newSquad, Color.white); 
}

Now you can set the squad colors in the inspector.


By the way: Using red and green for the two most used squads might not be the best decision, because of red/green color blindness. It affects about 10% of all genetically male people, making it the most common form of color-blindness. But that’s a different question.



Source link

More To Explore

Share on facebook
Share on twitter
Share on linkedin
Share on email