Random Selection Based on Percentage

Hi. I’m trying to setup a random selection of a few arrays but I’m having a problem. Here’s my script:

float chanceOfCurrency = 0.15f;
float chanceOfEnemies = 0.1f;
float chanceOfItem = 0.15f;

public Tile RandomTile()
{
	float random = Random.value;

	if (random < chanceOfCurrency)
	{
		return ChooseFrom(currencies);
	}
	else if (random < chanceOfEnemies)
	{
		return ChooseFrom(enemies);
	}
	else if (random < chanceOfItem)
	{
		return ChooseFrom(items);
	}
	else
	{
		return ChooseFrom(filler);
	}
}

The problem with this setup is that I need to place the variables in descending order. How can I setup this function where I can correctly choose based on actual percentages?

You can do it his way:

float chanceOfCurrency = 0.15f;
float chanceOfEnemies = 0.1f;
float chanceOfItem = 0.15f;
 
public Tile RandomTile()
{
    float random = Random.value;
 
    if (random < chanceOfCurrency)
    {
       return ChooseFrom(currencies);
    }
    else if (random < chanceOfCurrency + chanceOfEnemies)
    {
       return ChooseFrom(enemies);
    }
    else if (random < chanceOfCurrency + chanceOfEnemies + chanceOfItem)
    {
       return ChooseFrom(items);
    }
    else
    {
       return ChooseFrom(filler);
    }
}

Another way to do this is to precalculate each threshold and use your original code. So ‘chanceOfEnemies’ becomes 0.25, and chanceOfItem becomes 0.40.