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\$ Commented Apr 22, 2020 at 23:45
  • \$\begingroup\$ Yes! Precisely. \$\endgroup\$ Commented 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\$
2
  • 1
    \$\begingroup\$ For more information on how to elegantly implement weighted probabilities: How do I create a weighted collection and then pick a random element from it? \$\endgroup\$ Commented Apr 23, 2020 at 10:29
  • \$\begingroup\$ I second looking at what @Philipp commented; it's not particularly fun to maintain hardcoded magic numbers. \$\endgroup\$ Commented Apr 24, 2020 at 1:22

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.