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\$ – Panagiotis Iatrou Apr 22 '20 at 23:45
  • \$\begingroup\$ Yes! Precisely. \$\endgroup\$ – BroCodeNode Apr 23 '20 at 1:03
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.