Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Crixu · Oct 15, 2015 at 10:58 AM · c#unity 5instantiate

Create random order and go through till the end (C#)

I have a list of gameobjects (prefabs) that I want to randomly instantiate in order. I used GameObject[] to create the list and have specified the prefabs in the inspector. To obtain the next prefab to spawn I currently pick one at random from the list, but since I only want the items to occur once that isn't really helping.

I am still a beginner at C#, so I would like to have an example of how to do this with an easy way to adapt to possible future iterations.

Any help is always welcome!

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image meat5000 ♦ · Oct 15, 2015 at 12:29 PM 0
Share

Shufflebag

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Xarbrough · Oct 15, 2015 at 12:24 PM

Here is some simple code in the Start() method and some more ideas in some methods below. Save those other approaches for later, if they are confusing at this point.

One simple approach:

  1. Make a copy of the prefabs array. Use a list for easy resizing.

  2. As long as there are elements inside.

  3. Pick a random index from the list.

  4. Instantiate the random element.

  5. Remove it from the list, so it won't be picked again.

  6. Repeat (2).

    using UnityEngine; using System.Collections.Generic;

    public class Spawner : MonoBehaviour { public GameObject[] prefabs;

      private void Start () 
         {
             // Only try to instantiate, if prefab array was actually populated through the inspector.
             // This should always be the case, but maybe somebody does funky stuff with this script, so better check.
             if(prefabs != null)
             {
                 // Make a copy of the prefab array. A System.Collections.Generic List is easily resizable.
                 List<GameObject> spawnList = new List<GameObject>(prefabs);
     
                 // As long as there are elements in the collection.
                 while(spawnList.Count > 0)
                 {
                     // Pick a random index from the available options.
                     int randomIndex = Random.Range(0, spawnList.Count);
     
                     // If the element at the picked index exists, instantiate it.
                     if(spawnList[randomIndex] != null)
                     {
                         GameObject instance = Instantiate(spawnList[randomIndex]);
                         Debug.Log ("Created: " + instance.name + " " + instance.GetInstanceID());
                     }
     
                     // In any case, remove the random element from the list.
                     // This way it won't be instantiated again.
                     spawnList.RemoveAt(randomIndex);
                 }
             }
         }
         
         /// <summary>
         /// Instantiates any object collection of prefabs in random order.
         /// </summary>
         private void InstantiateInRandomOrder(IEnumerable<Object> prefabs)
         {
             if(prefabs == null)
                 throw new System.ArgumentNullException("prefabs", "Prefab collection cannot be null.");
     
             var spawnList = new List<Object>(prefabs);
     
             while(spawnList.Count > 0)
             {
                 int randomIndex = Random.Range(0, spawnList.Count);
     
                 if(spawnList[randomIndex] != null)
                 {
                     Object instance = Instantiate(spawnList[randomIndex]);
                     Debug.Log ("Created: " + instance.name + " " + instance.GetInstanceID());
                 }
         
                 spawnList.RemoveAt(randomIndex);
             }
         }
     
         /// <summary>
         /// Instantiates a generic collection of prefabs in random order and performs some action on each.
         /// </summary>
         private void InstantiateInRandomOrder<T>(IEnumerable<T> prefabs, System.Action<T> callback) where T : UnityEngine.Object
         {
             if(prefabs == null)
                 throw new System.ArgumentNullException("prefabs", "Prefab collection cannot be null.");
             
             var spawnList = new List<T>(prefabs);
             
             while(spawnList.Count > 0)
             {
                 int randomIndex = Random.Range(0, spawnList.Count);
                 
                 if(spawnList[randomIndex] != null)
                 {
                     T instance = Instantiate(spawnList[randomIndex]);
                     callback(instance);
                 }
                 
                 spawnList.RemoveAt(randomIndex);
             }
         }
     }
     
    
    
    
    
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Instantiate problem with selected objects 0 Answers

Why is my Prefab Instantiating when the Scene is Loaded? 2 Answers

Removing instantiated objects?? 1 Answer

Problem with Line Renderer 1 Answer

Multiple Cars not working 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges