Search Unity

Resolved Lists issues with adding, removing and randomizing.

Discussion in 'Scripting' started by Snakebearer, May 28, 2022.

  1. Snakebearer

    Snakebearer

    Joined:
    Feb 9, 2013
    Posts:
    26
    1. It doesn't return all of the prefabs into the new list. My experimenting told me that it should have removed everything but the background from the full list. But it actually keeps the three last prefabs in the list as well. I kinda know what's wrong, but I don't understand it. I figure it's related to removing from the list while inside its for loop. No idea how to go about it though. (Index 1 on the original list is the background graphics.)

    2. The values are not actually randomized. The list does return one of each size, (cept for the 8th one, described in the first issue), but they aren't random. Well, the three first ones are. But everything after those, keeps returning the same prefab whatever I do. So I figure I messed something up, or simply don't understand the usage of random.range or removerange in this instance.

    Code (csharp):
    1.  
    2.  
    3.     public int numberOfMeridiansOpen;
    4.     public List<GameObject> allRings;
    5.     public List<GameObject> randomRings;
    6.  
    7.  
    8.     void Awake()
    9.     {
    10.      
    11.  
    12.         allRings = new List<GameObject>(Resources.LoadAll<GameObject>("Rings"));
    13.  
    14.         randomRings = new List<GameObject>();
    15.  
    16.         for (int i = 0; i <allRings.Count; i++) {
    17.  
    18.             randomRings.Add(allRings[Random.Range(1,3)]);
    19.             allRings.RemoveRange(1,3);
    20.  
    21.     {
    22.  
    This version ain't working.




    edit:
    I got a message with the solution. I'm not too proud to show my failings. But I'll post the answer I got there here. In case someone else runs into the same silly issues I went into.

    1. Of course it doesn't return all of the items to the list. The for loop is too short because I keep shrinking the .Count with every loop. I hard set the count to 8 instead.

    2. In this instance, the variable I'm applying Random.Range to is an int, and not a float.. So it's max exclusionary. I.e, a value between 1 and 3 means it only returns a 1 or a 2.

    Code (csharp):
    1.  
    2.         for (int i = 0; i <8; i++) {
    3.  
    4.             randomRings.Add(allRings[Random.Range(1,4)]);
    5.             allRings.RemoveRange(1,3);
    6.  
    7.     {
    8.  
     
    Last edited: May 28, 2022
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Bunny83 likes this.