# How to spawn prefabs with percent random?

I need to instantiate 3 different prefabs.

First prefab must spawn with 50 %

Second prefab must spawn with 30 %

Third prefab must spawn with 20 %

I know how to intantite objects, but i didnt know how to make percent random.

Random.value returns a float between 0 to 1.
You can use it to generate percentage random like so:

``````if(Random.value > 0.5) //%50 percent chance
{//code here
}

if(Random.value > 0.2) //%80 percent chance (1 - 0.2 is 0.8)
{ //code here
}

if(Random.value > 0.7) //%30 percent chance (1 - 0.7 is 0.3)
{ //code here
}
``````

You can also say

if(Random.value <= 0.2)

to get a %20 chance without the confusion.

public float Chance()
{
float chances = new float { 0.5f, 0.3f, 0.2f }; // Your chances. Summary = 1.0f

``````    float randValue = UnityEngine.Random.value; // Randome value (chance value)

float currentChance = 0f;
float minChanceRange;
float maxChanceRange;

for (int i = 0; i < chances.Length; i++)
{
currentChance += chances*;*
``````

minChanceRange = 0.5f - currentChance / 2;
maxChanceRange = 0.5f + currentChance / 2;

if (randValue >= minChanceRange && randValue <= maxChanceRange)
{
return chances*; //code here*
}
}

return -1; //This code unreacheble
}