Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Having some trouble with arrays, not sure why.

Discussion in 'Scripting' started by Pythagoras64, Feb 14, 2015.

  1. Pythagoras64

    Pythagoras64

    Joined:
    Feb 10, 2015
    Posts:
    15
    I've written a little script that's meant to randomize a star's color. I'm using 3 arrays, with colors set in the inspector, and a random rarity value to choose which array to pick from.

    Code (CSharp):
    1.     public Color[] commonColors;
    2.     public Color[] rareColors;
    3.     public Color[] ultraRareColors;
    4.     int rarity;
    5.     Color chosenColor;
    6.     int index;
    7.  
    8.     void Start ()
    9.     {
    10.         rarity = Random.Range(0,20);
    11.  
    12.         if(rarity > 5)
    13.         {
    14.             index = Random.Range(0, commonColors.Length);
    15.             chosenColor = commonColors[index];
    16.         }
    17.         else if(rarity > 2)  
    18.         {
    19.             index = Random.Range(0, rareColors.Length);
    20.             chosenColor = rareColors[index];
    21.         }
    22.         else
    23.         {
    24.             index = Random.Range(0, ultraRareColors.Length);
    25.             chosenColor = ultraRareColors[index];
    26.         }
    27.  
    28.         particleSystem.startColor = chosenColor;
    29.     }
    Honestly, it works perfectly, my only concern however, is the errors it spits out in the console saying "IndexOutOfRangeException: Array index is out of range".

    I'm not really sure why this is happening; as far as I've seen searching around, I shouldn't be having any problems. I thought maybe using the array.length was setting the index outside of the array's actual length, and tried subtracting 1 from it, but that just made it not choose the last color in the array, and it still gave the error. Anyone here see what I've done wrong?
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    Error message tells you which line it's happening on. Which is it ? - I don't immediatly see anything wrong with the posted code
     
  3. orb

    orb

    Joined:
    Nov 24, 2010
    Posts:
    3,033
    The array index is zero-based. Try *.Length - 1, otherwise you're reading one step past the end.
     
  4. kdubnz

    kdubnz

    Joined:
    Apr 19, 2014
    Posts:
    177
    This advice is incorrect.
    The code as posted seems correct to me.

    Does it fail consistently ?
    Where does it fail ?

    Perhaps you could add some Debug.Log() statements to print the index and array.Length values to assist resolving this issue.

    //---
    Just to satisfy my curiosity,
    are these variables used elsewhere in the class than in the Start method.
    Code (CSharp):
    1.     int rarity;
    2.     Color chosenColor;
    3.     int index;
    They could be local scope ( defined inside ) the Start method if not used elsewhere.
     
  5. Pythagoras64

    Pythagoras64

    Joined:
    Feb 10, 2015
    Posts:
    15
    It's not consistent, no. It seems like only a quarter of the objects in the scene give the error, but they all occur on the lines where I set the chosen color. Also, the code in my post is the entire script for now, but I'll be using the rarity value later to define some other things. I'll put the other two into the start function though, and I'll try the debug.log idea and report back.
     
  6. Pythagoras64

    Pythagoras64

    Joined:
    Feb 10, 2015
    Posts:
    15
    Alright, so I gave it a shot adding Debug.Logs for the array lengths and also the index used, and as far as I can tell, there's absolutely no pattern to the errors, and all of the indexes are within the length of the array.

    I guess I can just get away with ignoring it for now; it doesn't seem to be affecting anything really, it's just clogging up the console.
     
    Last edited: Feb 15, 2015
  7. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    Array.Length is NOT 0 based, this means that if you call it on an Array with say 5 elements in it, it returns 5, while the maximum index is 4 (arrays are 0-based). Random.Range(min, max) is Inclusive, that means that the min and max value can be included. This means, that if you set index as Random.Range(0, Array.Length) the maximum selected value can be 5. However ,Array[5] would be out of range, and that is the issue you run in at the moment. What orb said is correct.

    sources:
    http://docs.unity3d.com/ScriptReference/Array.html
    http://docs.unity3d.com/ScriptReference/Random.Range.html
     
  8. kdubnz

    kdubnz

    Joined:
    Apr 19, 2014
    Posts:
    177
    Timelog,
    Sorry, you are both misunderstanding Random.Range()
    read the documentation again.

    public static function Range(min: float, max: float): float;
    Returns a random float number between and min [inclusive] and max [inclusive] (Read Only).

    public static function Range(min: int, max: int): int;
    Returns a random integer number between min [inclusive] and max [exclusive] (Read Only).
    If max equals min, min will be returned. The returned value will never be max unless min equals max.
     
  9. ReeVee

    ReeVee

    Joined:
    Feb 3, 2014
    Posts:
    5
    Your code looks good, best guess is that you may not have added color values to some arrays on the GameObjects that are throwing errors. So check to insure that each array on each GameObject has at least 1 color value. If you color arrays/values are going to be the same for all GameObjects you may want to define them in code.
     
  10. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    I ran into the same issue recently never 100% locked down why it was happening but you can do this to stop the errors:

    Code (CSharp):
    1.  
    2.     index = [URL='http://unity3d.com/support/documentation/ScriptReference/30_search.html?q=Random']Random[/URL].[URL='http://unity3d.com/support/documentation/ScriptReference/30_search.html?q=Range']Range[/URL](0, commonColors.[URL='http://unity3d.com/support/documentation/ScriptReference/30_search.html?q=Length']Length[/URL]);
    3.  
    4.     if(index >= commonColors.length){
    5.         index = commonColors.length-1;
    6.     }
    7.  
    8.     chosenColor = commonColors[index];
    9.  
    You are more correcting the problem after that fact but it will stop the errors for now
     
  11. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    Woops, completely missed that part :oops: way to late over here to concentrate :confused: It seems that in that case, the Random.Range does return a float value for whatever reason while it really shouldn't, and indeed, the code looks correct :/
     
  12. Pythagoras64

    Pythagoras64

    Joined:
    Feb 10, 2015
    Posts:
    15
    Hmm, interestingly enough, I copied my code over into a different script, and it seems to have completely stopped the error messages. Must have been some little glitch somewhere behind the scenes. Sorry to waste everyone's time; I'm fairly new to Unity, and I figured it had to be my fault somehow, heh.

    On the bright side though, I've learned a ton about how arrays work, so thanks for that!
     
  13. kdubnz

    kdubnz

    Joined:
    Apr 19, 2014
    Posts:
    177
    Regarding the comment by ReeVee
    Something like this may help.

    Code (CSharp):
    1.     public Color[] commonColors = new Color[] {
    2.                                                   Color.blue,
    3.                                                   Color.yellow,
    4.                                                   Color.magenta,
    5.                                                   Color.black,
    6.                                                   Color.white
    7.                                               };
    8.  
    9.     public Color[] rareColors = new Color[] {
    10.                                                 Color.red,
    11.                                                 Color.gray,
    12.                                                 Color.cyan,
    13.                                                 new Color32(128, 255, 128, 255)
    14.                                             };
    15.  
    16.     public Color[] ultraRareColors = new Color[] {
    17.                                                      Color.green,
    18.                                                      Color.cyan
    19.                                                  };
    20.  
    21.     private int rarity;
    22. //< .. >