Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 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
-1
Question by ShadyProductions · Jul 31, 2015 at 12:51 PM · listrandomremoveindexoutofbounds

Problems with removing a random from a list

I am trying to cycle through a list of enum variables and return a random one from it, then remove it from the list however some of them return index out of bounds and I can't get a workaround it can anyone help me? - Regards, Shady

 public enum Jobs {miner, builder, blacksmith, cook, None};
 public List<Jobs> availableJobs = new List<Jobs>();
 private Jobs toReturn;
 private Jobs _detach
         
 void Start() {
     foreach (Jobs jobs in Enum.GetValues(typeof(Jobs))) { //get all jobs into list
             availableJobs.Add(jobs);
     }
 }

 public Jobs lookForAvailableJob() { //function to find a job
     if(availableJobs.Count == 0) { //if list is empty
         availableJobs.Clear();
         return Jobs.None; //default
     } else { //if not
         _detach = availableJobs[Random.Range( 0, availableJobs.Count )]; //get a random
         for (int i=0; i < availableJobs.Count; i++) {
             if (availableJobs[i] == _detach) { //loop through to find the one
                 toReturn = availableJobs[i];
                 availableJobs.Remove(availableJobs[i]); //remove from list
                 print("removing: " +availableJobs[i]); //checking
             }
         }
     }
     return toReturn;
 }

 void Update () {
     if (lookForAvailableJob() == Jobs.None) {
         print("null");
     } else {
         lookForAvailableJob();
         //print(lookForAvailableJob());
     }
 }

I'm getting these kinds of outputs in the console

alt text

screenshot-1.png (16.0 kB)
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

2 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by NeverHopeless · Jul 31, 2015 at 01:09 PM

You lookForAvailableJob function needs some modification. Since you are removing an element from an array on which you are looping through. It is not advice-able to do it like this. Instead you can capture the element then either break the loop and delete it, or, delete it when it comes out of the loop. The one i am suggesting below does not force to implement loop.

  public Jobs lookForAvailableJob() { //function to find a job
      if(availableJobs.Count == 0) { //if list is empty
          availableJobs.Clear();
          return Jobs.None; //default
      } else { //if not
          _detach = availableJobs[Random.Range( 0, availableJobs.Count )]; //get a random
          availableJobs.Remove(_detach); //remove from list
      }
 
      return _detach;
  }



Comment
Add comment · Show 4 · 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 ShadyProductions · Jul 31, 2015 at 01:19 PM 0
Share

You're absolutely right, I figured that out after dns mentioned the break; that it wouldn't really need a loop. Thankyou!

avatar image ShadyProductions · Jul 31, 2015 at 01:29 PM 0
Share

However, is there another way to return a default value because now I have to do it this way but there is a chance that It will randomly take "none" a bunch of times and that will prolong the removal of the other jobs

         _detach = availableJobs[Random.Range( 0, availableJobs.Count )]; //get a random
         if(availableJobs.Count == 0) { //if list is empty
             availableJobs.Clear();
             return Jobs.None; //default
         } else if (_detach == Jobs.None) { //if not
             return Jobs.None;
         } else {
             availableJobs.Remove(_detach); //remove from list
         }        
         return _detach;
avatar image NeverHopeless · Jul 31, 2015 at 01:46 PM 0
Share

Perhaps this:

 detach = availableJobs[Random.Range(0, availableJobs.Count )]; //get a random
 if(availableJobs.Count == 0) { //if list is empty
     availableJobs.Clear();
 } else if (_detach != Jobs.None) { //if not
    availableJobs.Remove(_detach); //remove from list
    return _detach;
 }        
 return Jobs.None;
avatar image ShadyProductions · Jul 31, 2015 at 01:56 PM 0
Share

Thanks that might be easier yes.

avatar image
1

Answer by _dns_ · Jul 31, 2015 at 01:07 PM

Hi, i guess the problem is the line 22: you "print" the name of the element i just after removing it! If you remove the last element of the list you can't print it's value after removing it! Also, the text displayed will be wrong for other elements = you remove element i but will display the name of element i+1 (because you just removed element i)

Also, no need to continue to iterate after you removed the element. A "break" statement would be fine here.

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 ShadyProductions · Jul 31, 2015 at 01:11 PM 0
Share

Wow switching 1 line and adding a break; did alot, thankyou it is fixed. I guess I was a little bit too into it, that I didn't notice I placed the print call after I deleted the object. :/ And I am ashamed I didn't use the break method

avatar image _dns_ · Jul 31, 2015 at 01:14 PM 0
Share

Well, didn't look at the efficiency of your code: NeverHopeless answer should be better (and fix the bug as well ;-)

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

23 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Is it possible to grab an index in a List by random as in arrays? 2 Answers

How can I display 4 items in random order but never double? 2 Answers

A node in a childnode? 1 Answer

Making a camera list 1 Answer

How to assign a variable individually for each element of an object list 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