# How can I make an instantiation random?

I'm trying to do it so when I have an instantiated an item upon the game starting, it is random as to whether it actually instantiates or not. Here's the code I have so far:

public GameObject anyItem;
void Start()
{
Instantiate(anyItem, new Vector3(0, 0, 0), Quaternion.identity);
Instantiate(anyItem, new Vector3(11, 0, 0), Quaternion.identity);
}


How can I do it so these items (individually, not both together) are decided randomly as to whether they will actually be instantiated or not?

• Can you further explain what you are trying to achieve? Do you want to assign a certain probability as to whether an object gets instantiated? – Panagiotis Iatrou Apr 22 '20 at 23:45
• Yes! Precisely. – BroCodeNode Apr 23 '20 at 1:03

You can use Random.Range(0, 100) to get a random int from 0 to 100 for example. You then just need a probability for each GameObject you're trying to instantiate.

public GameObject anyItem;

void Start()
{
// There is a 60% chance for a new object
randomlyInstantiateAtPosition(60, new Vector3(0, 0, 0));
// There is a 25% chance for a new object
randomlyInstantiateAtPosition(25, new Vector3(11, 0, 0));
// This one will always be made
randomlyInstantiateAtPosition(100, new Vector3(22, 0, 0));
}

private void randomlyInstantiateAtPosition(int probability, Vector3 position) {
if (Random.Range(0, 100) < probability) {
Instantiate(anyItem, position, Quaternion.identity);
}
}


Here's the documentation for Random.Range:

https://docs.unity3d.com/ScriptReference/Random.Range.html