0
\$\begingroup\$

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?

\$\endgroup\$
2
  • \$\begingroup\$ 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? \$\endgroup\$ Apr 22, 2020 at 23:45
  • \$\begingroup\$ Yes! Precisely. \$\endgroup\$ Apr 23, 2020 at 1:03

1 Answer 1

1
\$\begingroup\$

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

\$\endgroup\$
3

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .