Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 StewartB · Aug 31, 2013 at 09:00 PM · arraysinventoryfor-loopinventory systemindexoutofrangeexception

Array index is out of range?

I'm writing up a basic inventory script based on an array of GameObjects. This is just coding practise, so I'll probably just release it when I'm done for others to use. This is my Inventory script, applied to a standard First Person Controller:

 using UnityEngine;
 using System.Collections;
 
 public class Inventory : MonoBehaviour
 {    
     public bool inventoryScreenEnabled = false;
     public bool isHoldingSomething = false;
     public GameObject heldItem = null;
     public int maxSlots = 9;
     public GameObject[] InventoryContents = new GameObject[9];
     
     public Transform holdPos;
     
     void Start()
     {
         Screen.showCursor = false;
         Screen.lockCursor = true;
     }
     
     void Update()
     {
         if (Input.GetKeyDown(KeyCode.M))
         {
             if (inventoryScreenEnabled == false && heldItem == null)
             {
                 EnableInventory();
             }
             else if (inventoryScreenEnabled == true)
             {
                 DisableInventory();    
             }
         }
         if (Input.GetButtonDown("Fire2") && heldItem != null)
         {
             heldItem.transform.parent = null;
             heldItem.GetComponent<PickUp>().enabled = true;
             heldItem.GetComponent<Rigidbody>().useGravity = true;
             heldItem.GetComponent<Rigidbody>().isKinematic = false;
             heldItem = null;    
         }    
     }
     
     void EnableInventory()
     {
         this.transform.GetComponent<CharacterMotor>().enabled = false;
         this.transform.GetComponent<MouseLook>().enabled = false;
         Camera.mainCamera.GetComponent<MouseLook>().enabled = false;
         inventoryScreenEnabled = true;
         Screen.showCursor = true;
         Screen.lockCursor = false;
     }
     
     void DisableInventory()
     {
         this.transform.GetComponent<CharacterMotor>().enabled = true;
         this.transform.GetComponent<MouseLook>().enabled = true;
         Camera.mainCamera.GetComponent<MouseLook>().enabled = true;
         inventoryScreenEnabled = false;    
         Screen.showCursor = false;
         Screen.lockCursor = true;
     }
     
     void OnGUI()
     {
         if (inventoryScreenEnabled == true)
         {
             GUI.BeginGroup (new Rect (Screen.width / 2 - 150, Screen.height / 2 - 150, 300, 300));
             GUI.Box(new Rect(0,0,300,300), "Inventory");
             for(var i = 0; i < 9; i++)
             {
                 if (InventoryContents[i] != null)
                 {
                     if (GUI.Button(new Rect(10,30,280,25), InventoryContents[i].name))
                     {
                         Debug.Log("Item pressed!");
                         heldItem = InventoryContents[i];
                         InventoryContents[i] = null;
                         heldItem.SetActive(true);
                         heldItem.transform.parent = holdPos;
                         heldItem.transform.position = holdPos.transform.position;
                         heldItem.transform.rotation = holdPos.transform.rotation;
                         heldItem.GetComponent<Rigidbody>().useGravity = false;
                         heldItem.GetComponent<Rigidbody>().isKinematic = true;
                         DisableInventory();
                     }    
                 }
             }
         }
     }
 }

And this is the PickUp script, applied to each item that can be added to the inventory:

 using UnityEngine;
 using System.Collections;
 
 public class PickUp : MonoBehaviour
 {
     public GameObject playerObject;
     private Inventory inventory;
         
     void Start()
     {
         inventory = playerObject.GetComponent<Inventory>();    
     }
     
     void OnMouseDown()
     {
         if (inventory.inventoryScreenEnabled == false && inventory.heldItem == null)
         {
             for(var i = 0; i < inventory.maxSlots; i++)
             {
                 if (inventory.InventoryContents[i] == null)
                 {
                     inventory.InventoryContents[i] = this.gameObject;
                     transform.parent = playerObject.transform;
                     transform.position = playerObject.transform.position;
                     enabled = false;
                     this.gameObject.SetActive(false);    
                 }
             }    
         }
     }
 }

It all works fine until I actually pick up an object, at which point I get that error: "Array index is out of range."

Can anyone tell me what I'm doing wrong?

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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by DESTRUKTORR · Aug 31, 2013 at 09:04 PM

Firstly, you'll want to see what specific line this is happening from (the error report should notify you of which line it came from, as well if you double-click it, it will automatically open that file, scroll to that line, and highlight it for you).

However, an "array index out of bounds" error means that either you've tried to access an array member that is less than 0 (which is impossible, as array indices start at 0, and only increase in value from there) or you used a value that is too large.

Given that in the first section of code you used a 9 literal in your for loop (the only place in that section where the array was accessed), the error could no be coming from there.

However, you used the variable "maxSlots" in the second bit of code, which, my best guess, was changed somewhere to be a value that is either negative, or too large for the inventory array.

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 StewartB · Aug 31, 2013 at 09:06 PM 0
Share

Oh, sorry, I forgot to mention that the error was in line 71 of the inventory script.

Yeah, I was trying to use maxSlots in place of a literal 9 (you know, for customisability) but that didn't seem to work for some reason.

The variable maxSlots is not changed anywhere.

avatar image StewartB · Aug 31, 2013 at 10:15 PM 0
Share

Okay, I made a temporary fix by changing the for loop in each script to

 for(var i = 0; i < 8; i++) 

That works perfectly except I can only add one item to the inventory at a time. If I try to add a second, it doesn't work, no error shown.

I also added GUI.EndGroup(); to the end of the OnGUI() function in the inventory script as it was throwing an error.

Any idea why the inventory can't add more than 1 item?

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

17 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

Related Questions

Not all code paths return a value? 1 Answer

[C#]For-loop in For-loop crashes Unity. 1 Answer

[C#]Inventory script help. 3 Answers

Is this considered bad coding 1 Answer

Why does my array only execute the last of the array? 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