0
\$\begingroup\$

I'm wondering how to make specific random objects drop. In my case, from the top of the screen.

I have 16 objects, named recycle_items_0 through recycle_items_15.

IEnumerator CreateRoutine()
{
    while (true)
    {
        yield return new WaitForSeconds(3);
        CreateItems0();
    }
}

private void CreateItems0()
{
   Vector3 pos = Camera.main.ViewportToWorldPoint(new Vector3(UnityEngine.Random.Range(0.0f,1.0f),1.1f,0));
   pos.z = 0.0f;
   Instantiate(recycle_items_0, pos, Quaternion.identity);
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Put your 16 items into an array, then select a random element of that array.

// Populate this array in the inspector.
public GameObject[] _prefabs;

private void CreateRandomItem()
{
   Vector3 pos = Camera.main.ViewportToWorldPoint(new Vector3(UnityEngine.Random.Range(0.0f,1.0f),1.1f,0));
   pos.z = 0.0f;

   var prefab = _prefabs[Random.Range(0, _prefabs.Length)];

   Instantiate(prefab, pos, Quaternion.identity);
}

Any time you find yourself appending a number to the end of a name, stop and ask yourself, "is this a place where I should use an Array, List, or other collection instead of individually-named variables?"

\$\endgroup\$

You must log in to answer this question.

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