1

enter image description hereI am making a RISK game in unity. I have 42 sprites of countries, and I have to generate random colors for each one, for example for 2 players 21 green and 21 red.

How can I generate color randomly ?

{
    this.GetComponent<SpriteRenderer>().color = Color.green;
}
    else
{

    this.GetComponent<SpriteRenderer>().color = Color.red;
}
Awais Chaudhry
  • 47
  • 1
  • 1
  • 9

2 Answers2

2

This can easily be done with Unity's UnityEngine.Random.Range function.. Generate Random number between 0 and 1. Make 0 to be red and 1 to be green.

Color getRandomColor()
{
    //0 = red
    //1 = green
    if (UnityEngine.Random.Range(0, 2) == 0)
        return Color.red;
    else
        return Color.green;
}

Usage:

this.GetComponent<SpriteRenderer>().color = getRandomColor();

EDIT:

I deploy them equally

I guess you mean generate the random number equally. 12 red and 12 green and the-same time randomly.

Use this class:

public class EquallyColorGen
{
    const int totalNumber = 24;

    static bool[] randomNumbers = new bool[totalNumber];
    static Color[] randomColor = new Color[totalNumber];

    public static Color[] generateRandomNumbers()
    {
        const int halfOfTotalNumber = totalNumber / 2;

        int firstRandom = UnityEngine.Random.Range(0, 2);

        bool first12;
        bool last12;

        if (firstRandom == 0)
        {
            first12 = true;
            last12 = false;
        }
        else
        {
            first12 = false;
            last12 = true;
        }

        //Generate Even Random number. The first 12 are the-same. The last 12 are different but the-same
        for (int i = 0; i < randomNumbers.Length; i++)
        {
            randomNumbers[i] = (i < halfOfTotalNumber) ? first12 : last12;
        }

        //Shuff Amount
        const int shuffleAmount = 1;

        for (int j = 0; j < shuffleAmount; j++)
        {
            for (int i = 0; i < halfOfTotalNumber; i++)
            {
                //0 = flip color
                int randColor = UnityEngine.Random.Range(0, 2);
                bool flip = false;

                flip = (randColor == 0) ? true : false;

                //Also flip the 1 to 12
                randomNumbers[i] = (flip == true) ? !randomNumbers[i] : randomNumbers[i];

                //Also flip the other side 12 t0 24
                int lIndex = i + halfOfTotalNumber;
                randomNumbers[lIndex] = (flip == true) ? !randomNumbers[lIndex] : randomNumbers[lIndex];
            }
        }

        //Finally Make color from the list
        for (int i = 0; i < randomNumbers.Length; i++)
        {
            //Red = false
            //Green = true
            randomColor[i] = (randomNumbers[i] == false) ? Color.red : Color.green;
        }

        return randomColor;
    }
}

Usage:

Color[] randomPlayerColors = EquallyColorGen.generateRandomNumbers();

There are 24 random colors in the randomPlayerColors variable and they are generated equally. If you want 42 random colors, simply change const int totalNumber = 24; to const int totalNumber = 42;

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • 1
    You can also use `Random.value` like `Color c = Random.value < 0.5f ? Color.red : Color.blue` – Iggy Apr 23 '17 at 11:10
  • 1
    @Iggy Yes, you can. I could have but by reading the question, OP seems to be new to C# and I think the `if` statement will make it easier to understand what I did instead of ternary operator. – Programmer Apr 23 '17 at 11:17
  • thanks , yes i am new to unity C# and it helped a lot , but there is a problem number of green and red countries are not equal some times green countries are more than red and some times red are more than green,, how can i deploy them equally ? they have tag of "country" how can i add them in an array so i can compare them.. @Programmer – Awais Chaudhry Apr 24 '17 at 10:53
  • 42 sprites of country, i tagged them as country,,, but the main problem is that i can't assign color equally , 21, 21 each @Programmer – Awais Chaudhry Apr 24 '17 at 11:00
  • Check my edited answer. That's hard to do but answer is there. – Programmer Apr 24 '17 at 12:27
  • this is not working, i might sound dumb , but how can i access sprites which are in my game scene to my code (array) ? i guess that is the problem **i added a screenshot in my question edited-** @Programmer – Awais Chaudhry Apr 25 '17 at 06:37
  • Please do **not** ask a question that has nothing to do with your original question. This is making the comment section unnecessary long. It is also wasting both of our times. You can ask a new question for a different problem. – Programmer Apr 25 '17 at 06:53
  • Like my modified question, you generate 24 random numbers like this: `Color[] randomPlayerColors = EquallyColorGen.generateRandomNumbers();`. In this array, you can use 0 to 11 index for player 1 and 12 to 23 for player 2. – Programmer Apr 25 '17 at 06:54
  • Since you mentioned that you you need 42 sprites, 21 for each player.....Change `const int totalNumber = 24;` to `const int totalNumber = 42;`. Get random colors with `Color[] randomPlayerColors = EquallyColorGen.generateRandomNumbers();`. Now, use '0' to `23` index for player one and '24' to '41' index for player 2. What is so hard about this? `Player1Color = randomPlayerColors[0]`, ... `AnotherPlayer1Color = randomPlayerColors[1]`.... – Programmer Apr 25 '17 at 06:57
0

Well I would make a different approach.

A controller object (not a sprite, just an invisible object that will hold some necessary scripts as in editor game logic interfaces) should have a script that will get all country GameObjects and shuffle them randomly in a list and divide between colors of how many players there are (like first half to a player 1, second...)

To shuffle a list:

List<CountryScript> countryList = new  List<CountryScript>();
countryList.AddRange(GetComponents<CountryScript>());
List<CountryScript> shuffledCountryList = new  List<CountryScript>();
while(countryList.Count > 0) {
    CountryScript c = countryList[Random.Range(0, countryList.Count)];
    shuffledCountryList.Add(c);
    countryList.Remove(c);
}

At the end of this you have an empty countryList and full shuffledCountryList. Any devision you can do in foreach loop like:

int playerCount = 2;
int maxNum = shuffledCountryList.Count / playerCount;
//It can be 2 or whatever you'll have it later
for(int i = 0; i < shuffledCountryList.Count; i++) {
    shuffledCountryList[i].SetPlayer(i/maxNum);
}

The CountryScript should have a public void SetPlayer(int Num) {} method that will color to a player specific color by an int Num value. Will you store this list on that Controller script in a property to be able to tweak it in editor or have it hardcoded in CountryScript is your choice. I'd go first way, since this way you can easily add more players + edit without coding. Or like Programmer wrote:

(Num == 0) ? Color.red : (Num == 1) Color.green : Color.blue;

Hope this helped you.

zORg Alex
  • 372
  • 2
  • 15
  • yeah it seems good bcoz after some time i have to add more players in it , but i got few errors like . **i am new to unity c#**.. " Error CS0246 The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) " "Error CS0246 The type or namespace name 'CountryScript' could not be found (are you missing a using directive or an assembly reference? " , i posted a screenshot in my question now @zORg Alex – Awais Chaudhry Apr 25 '17 at 06:54
  • Well yes. List is in System.Collections.Generic. You need to add a using System.Collections.Generic; – zORg Alex Apr 25 '17 at 07:39
  • And about second one. You need to create a new script with that name and attach to your Country objects. As I've said in my answer. I was not going to write everything. I hope you will try to do it. I can help you out though. You will need to study scripting in unity tutorials. They will explain a lot of good things. Like how to organize scripts, how to do simple things. – zORg Alex Apr 25 '17 at 07:46
  • I prefer to have a script to almost every GameObject type in a game. It just helps to differentiate them in code by GetComponent() + it will be easy to add some functionality to any of them in any time. + Use MS Visual Studio. Ctrl+'.' will help you to solve things. It's easy to add needed usings with Ctrl+'.' or even generate new classes. Unity Scripts will be more complicated, because they will need to be set to public, derived from MonoBehaviour etc. I'm not sure how to setup MonoBehaviour template. Hmm... a good question though. – zORg Alex Apr 25 '17 at 07:53
  • only one error left, Error CS1061 'SpriteRenderer' does not contain a definition for 'SetPlayer' and no extension method 'SetPlayer' accepting a first argument of type 'SpriteRenderer' could be found (are you missing a using directive or an assembly reference? – Awais Chaudhry Apr 25 '17 at 08:05
  • Did you use GetComponents() ? You should have a List(), but not a List. To look what type of a variable you have, try hovering mouse pointer over a variable. – zORg Alex Apr 25 '17 at 08:15