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 tapcolour · Oct 02, 2019 at 03:38 PM · instantiatearraysgameobjectsarray-out-of-range-except

I'm getting an index out of range error even though my arrays are filled with elements?

So in my game, I'm trying to randomly spawn objects with weighted probability and when I run the game, it gives me an "Array out of index range" exception. I've been trying for so long to get rid of this error, but I don't understand why this is happening.

I have 2 arrays that are both filled with elements (I checked myself) which are required. But when I check compare the lengths of the arrays, it says "False" even though I'm not changing them. Both arrays are filled with elements via the inspector.

It throws the error when I'm trying to instantiate the objects.

Essentially all trying to do is spawn objects randomly according to their probability weights in random locations.

Here is the code:

  public GameObject[] fruits; 
     //Array of probability weights for each fruit
     public int[] Weights; 
 
 IEnumerator Spawn ()
     {
         while(endGame == false)
         {
             Vector3 spawnPoint = new Vector3(Random.Range(-9, 9), 5, 0);
 
             //This is to store the total sum of the weights each fruit has 
             int totalWeight = 0;
 
             foreach(int weight in Weights)
             {
                 //Adds each weight to calculate the total sum of the array
                 totalWeight += weight;
             }
 
             //Generate a random number between 0 and the sum of all weights
             randomWeight = Random.Range(0, totalWeight);
 
             foreach(int fruit in weights)
             {
                 if (randomWeight < fruit)
                 {
                     //Instantiate the fruit from the value generated from randomWeight
                     //This instantiate line is what throws the error
                     Instantiate(fruits[randomWeight], spawnPoint, transform.rotation);
                 }
                 else
                 {
                     randomWeight -= weight;
                 }
             }
 
             Debug.Log("Size of  weights AFTER loop " + weights.Length); 
             //Checks if both arrays are equal to each other
             Debug.Log(fruits.Equals(Weights)); 
 
             yield return new WaitForSeconds(1f);

Appreciate the help. Thanks

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 Hellium · Oct 02, 2019 at 04:51 PM

 randomWeight = Random.Range(0, totalWeight);
  
 for(int i = 0 ; i < Weights.Length ; ++i)
 {
     if (randomWeight < Weights[i])
     {
         //Instantiate the fruit from the value generated from randomWeight
         Instantiate(fruits[i], spawnPoint, transform.rotation);
         break; // Thanks Bonfire-Boy for the heads-up
     }
     else
     {
         randomWeight -= Weights[i];
     }
 }


And by the way Debug.Log(fruits.Equals(Weights)); does not compare the lengths of the array. You will always have false in the console... If you want to compare the length, use Debug.Log(fruits.Length.Equals(Weights.Length)); (or more simply Debug.Log(fruits.Length == Weights.Length); )

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 Bonfire-Boy · Oct 02, 2019 at 05:02 PM 1
Share

I think you also need to break out of the loop after instantiating.

Take the case where randomWeight comes out as zero... it'll be less than all the weights and they'll all get spawned.

(I realise this is something inherited from the OP btw)

avatar image Hellium Bonfire-Boy · Oct 02, 2019 at 09:12 PM 0
Share

Oh yes, you are totally right, fixed the code!

avatar image Bonfire-Boy · Oct 02, 2019 at 05:07 PM 2
Share

Oh and a by-the-by for the OP: separate arrays for fruits and weights is a really bad idea. Not only do you have to check they're the same length but also it's horrid for matching fruits with their weights in the inspector. In a situation like this it's very easy to do something along these lines:

 [Serializable]
 public class WeightedFruit
 {
     public GameObject fruit;
     public int weight;
 }
 
 public WeightedFruit[] weightedFruits;

avatar image tapcolour · Oct 02, 2019 at 09:31 PM 0
Share

Thank you, it's working properly now! I can't believe all I had to do was change it to a for loop and put a break in. I also appreciate being shown how to make the code more efficient Bonfire-Boy so thanks for that too!

avatar image
0

Answer by tormentoarmagedoom · Oct 02, 2019 at 04:42 PM

Hello there.

I did not read all your post, only the title.

But if you are getting an out of range error, is gecause of that, an index is out of the range.

if you have a array with 4 elements, and try to read the 5th element, will get that error, because the index can be up to 3 (remember 1st element is index=0). No other things to look for or find. Is just that.

Check carefull your code, debug it, and will see where is the error.

Good luck!

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

140 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 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 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 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 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 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 avatar image avatar image

Related Questions

instantiate gameobject[] 1 Answer

Instantiate 1 at a time at each transform in array 1 Answer

How to spawn objects from CSV file 1 Answer

IndexOutOfRange error on iPhone, but not on PC/Player 0 Answers

Cannot find the length of an array 3 Answers


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