Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 matias-e · Apr 09, 2015 at 04:06 AM · c#arraytag

Only instantiate GameObjects with a certain tag from an array

Hi. I'm trying to create a bit of code that instantiates only game objects from an array that are not already active in the game view. What I have at the moment is something that gives a tag to the spawned game object and I'm trying to exclude the ones with a Spawned tag from the random number generator's choices. Here's a some of the code:

     void SpawnPerson () {
      
             int randNum = RandomGen();
      
             Vector3 randomPosition = new Vector3
                 (
                     Random.Range (boundary.xMin, boundary.xMax),
                     Random.Range (boundary.yMin, boundary.yMax),
                     -1.25f
                 );
      
             if(CubeMover.keepClosed == false)
             {
                 GameObject person = Instantiate
                     (
                         personArray[randNum],
                         randomPosition,
                         Quaternion.identity
                     )
                         as GameObject;
             }
      
             personArray[randNum].tag = "Spawned";
         }
      
      
         int RandomGen () {
      
             int i;
      
             i = Random.Range(0, personArray.Length);
      
             return i;
      
         }
     }
 
Comment
Add comment
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

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by supernat · Apr 09, 2015 at 04:37 AM

You can't really do it by using the tag, because you would have to do something like a while loop and continue generating random indices into the personArray until you get to one that doesn't have the tag "Spawned", which would grow exponentially as you continued.

A solution to this problem that I've done myself is to create a List containing the index from 0 to PersonArray.Length-1 as list elements, like this:

 List<int> possibleChoices = new List<int>(PersonArray.Length);
 for (int i=0; i < PersonArray.Length; ++i)
     possibleChoices.Add(i);

Then you can random pick an element from this list:

 int index = Random.Range(0, possibleChoices.Count);
 possibleChoices.RemoveAt(index);
 PersonArray pa = personArray[index];
 // Use pa

So possibleChoices gets reduced in size over time but always only contains the unspawned item indices into personArray. You will probably also want to check that possibleChoices.Count is greater than 0 and re-add all indices back to it when it hits count of 0.

Comment
Add comment · Show 2 · 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
avatar image matias-e · Apr 10, 2015 at 11:12 AM 0
Share

That looks superb!

Let's see if I got what it does, trying to clear it up for myself.. So, the for loop adds as many sequential int numbers to the 'possibleChoices' array as there are spaces in the PersonArray.

Then it picks a number between 0 and the length of the possibleChoices array, after which the chosen number is deleted from the amount of possible choices (but it only affects the next round the pick happens as the number has already been chosen) and the picked index number is then used to refer to a slot in the PersonArray.

avatar image supernat · Apr 10, 2015 at 02:38 PM 0
Share

Yep, that sounds right. It gets a little confusing when you start storing lists of indices that index into a list of ints (but you have a list of objects, so less confusing). :) Just carefully walk through it, and it should make sense when you apply it to your context. I didn't state this clearly, but if you wanted to reduce the set of possible choices every time you instantiate, you would create the possibleChoices list in the Start method. Then check in Update or just after you call possibleChoices.RemoveAt(index) if possibleChoices.Count == 0. If so, re-populate it with everything from PersonArray. Then you have a guaranteed random yet unique item pulled out each time you instantiate, and it refills itself when it gets empty.

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Attacking more than one enemy with same tag, but unity only allows one enemy at a time? 2 Answers

Question about FindObjectsOfType 1 Answer

Removing and Adding gameobjects to an array upon collision 1 Answer

How can I make a GameObject face a GameObject with a specific Tag? 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