I am developing an infinite runner using Unity. I have already figured out how to loop a set of backgrounds randomly but I am having problems doing the same for the objects.

So, I have a few objects or obstacles in my prefabs. I want them to generate randomly in the game, not everything at once though.

How do I do that? Can I please get a well-explained piece of code for the purpose?

EDIT : I want the objects to be destroyed as soon as they move out of camera's view (The cam which is following the player).

Thank you.

  • \$\begingroup\$ Your question is how to select a random object from a collection of objects ? Add the objects in a list, calculate a random int (the index) from 0 to list.size - 1 and select the item with that index. \$\endgroup\$
    – dimitris93
    Sep 14 '15 at 4:14
  • \$\begingroup\$ A little more precision would be appreciated. I am just a beginner. Also, I want the objects generated to be in contact with the floor. \$\endgroup\$
    – Hardik
    Sep 14 '15 at 4:15
  • \$\begingroup\$ I don't have experience with unity to help you with the exact code. But if you are trying to select a random object from a list of objects. You can simply generate a randomInt from 0 to list.size - 1 and get the random object from list.getAtIndex(randomInt) \$\endgroup\$
    – dimitris93
    Sep 14 '15 at 4:34
  • \$\begingroup\$ @Shiro Hmm, true. But I think it's not the best way to so it, additionally, I want that particular object to be destroyed after it gets out of view. Thanks though ;thumbsup; \$\endgroup\$
    – Hardik
    Sep 14 '15 at 4:36
  • \$\begingroup\$ It is the only way to do it. If your concern is about pre-creating those objects, you could have just a list of strings with the path to the prefabs instead. \$\endgroup\$
    – dimitris93
    Sep 14 '15 at 4:49

Load an array with all your prefabs (In the examples the prefabs are all into the same folder)

public List<GameObject> items;     
void Start()
         // If you store all your items that you want to load in the same folder (Assets/Resources/MyItemsToLoad).
         items = Resources.LoadAll("MyItemsToLoad") as GameObject[];

When you need to random instantiate them

    int prefabIndex = UnityEngine.Random.Range(0,items.Count-1);
        Instantiate(items[prefabIndex], _position, _rotation);

Then put an empty gameobject with a "isTrigger" collider past camera view (i think you can make it child of camera):

enter image description here

Each obstacle object needs a script attached like this

 void OnCollisionEnter( Collision collision ) {

         if( collision.trasform.tag = 'DestroyTriggerCollider' ) {

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.