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 BloodEchelon · Jun 18, 2017 at 11:15 AM · buttonarraylistenerindexoutofrangeexception

Mysterious IndexOutOfRangeException

Hi guys!

Currently I'm working on a little sidescrolling game. It focuses on the player unlocking different units and sending them from their base to destroy the enemy base.

When a player has an unit unlocked and enough resources for it they can click the units button in the UI and it will be put in a queue, since only 1 unit can be trained at a time. When the player does this the game creates a queue button that can be clicked to remove the unit from the queue and refund it's costs. For this I'm using these 2 possibilities (depending on if there are already units in the queue).

 QueueButtons [0] = Instantiate (QueuePrefabs[unit], new Vector3 (1216f, 952f, 0f), Quaternion.identity, QueueMenu);
 QueueButtons [0].GetComponent<Button> ().onClick.AddListener (delegate {
                         CancelUnit(0);
 });

 for (int i = 0; i < training_queue.Length; i++) {
    if (training_queue [i] == -1) {
       QueueButtons [i] = Instantiate (QueuePrefabs [unit], new Vector3 (1216f / 2f + 160f * i, 952f, 0f), Quaternion.identity, QueueMenu);
       QueueButtons [i].GetComponent<Button> ().onClick.AddListener (delegate {CancelUnit (i);});
    i = training_queue.Length;
    }
 }

But every time I try to use a button created by the second method Unity gives me this error message:

 IndexOutOfRangeException: Array index is out of range.
 PlayerCastle.CancelUnit (Int32 queue_slot) (at Assets/Scripts/PlayerCastle.cs:159)
 PlayerCastle+<TrainUnit>c__AnonStorey0.<>m__0 () (at Assets/Scripts/PlayerCastle.cs:135)
 UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:154)
 UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:637)
 UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:773)
 UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:52)
 UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
 UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
 UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
 UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
 UnityEngine.EventSystems.EventSystem:Update()
   

(The line meant here is:
if (training_queue [queue_slot] != -1) {
)

Queue_slot stands for an int the method CancelUnit this line is in, requires. It is the same number I gave the buttons in the AddListener functions.
Normally this error would mean my value I tried to put would be too large for the array training_queue, wouldn't it? But it actually can't be larger since my for statement only allows i to be smaller than training_queues' size.

What am I missing/doing wrong? If you need additional info just tell me, I didn't want to post my complete class code since its over 200 lines.

Thank you in advance!

Comment
Add comment · Show 2
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 toddisarockstar · Jun 18, 2017 at 02:26 PM 0
Share

the computer is never wrong. queue_slot is going higher that the array or less that zero. you just got to figure out why. i would put something like this directly before the error line to help you confirm the problem.

 if (training_queue.Length<=queus_slots){
 print("error because cause :"training_queue.Length + "  < " + queus_slots);}


this would tell you if there is a problem with the array not initialized as you intend or if its the index you are asking for

avatar image BloodEchelon toddisarockstar · Jun 18, 2017 at 02:55 PM 0
Share

Thanks for your help! I tried this out and found something weird: All the buttons (except the first) receive the value 11 as argument for their action (CancelUnit), but digging into the point where these buttons are created I found out that when I check for 'i' it still counts correctly:

 print ("I: " + i);
 QueueButtons [i] = Instantiate (QueuePrefabs [unit], new Vector3 (1216f / 2f + 160f * i, 952f, 0f), Quaternion.identity, Queue$$anonymous$$enu);
 QueueButtons [i].GetComponent<Button> ().onClick.AddListener (delegate {
    CancelUnit (i);
 });

Going through the for statement (this piece of code is in) I get the outputs 1, 2, 3... 9 but still get the error when trying to use the buttons.

It seems to be a problem with AddListener... Are there other possibilities to use ins$$anonymous$$d of AddListener or did I mess things up here (like: should I use something else ins$$anonymous$$d of delegate ...)?

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by FlaSh-G · Jun 18, 2017 at 09:49 PM

Even though it's probably possible to somehow find the error, it's a good idea to move away from multiple Arrays having the same length. Having these will lead to hard-to-detect errors sooner or later.

The trick is to create a class or struct that combines the values of all arrays on a specific index and then create a single array that contains these objects.

So instead of

 public int[] playerIDs;
 public string[] playerNames;

you do

 [System.Serializable]
 public struct Player
 {
   int id;
   string name;
 }

and then

 public Player[] players;

This way, you only have one array and your for loop can go

 for(var i = 0; i < players.Length; i++)
 {
   players[i].This();
   players[i].That();

instead of

 for(var i = 0; i < someArray.Length; i++)
 {
   anotherArray[i].Stuff();
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

82 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

Related Questions

Camera movement - index out of range 1 Answer

C# For loop in button to set gameObjects in array to active 1 Answer

My onclick action listeners I attach to my buttons as I instantiate them only work once 1 Answer

Displaying object with button 1 Answer

IndexOutOfRangeException: Array index is out of range when using an Array and instantiating 2 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