Having the error: ArgumentOutOfRangeException: Argument is out of range.

I am creating a chest, but when i press the interact key (e) it comes up with this error:

ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List`1[inventory].get_Item (Int32 index) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:633)
ChestGUI.OnGUI () (at Assets/Scripts/Inventories/GUI/ChestGUI.cs:29)

My Code:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ChestGUI : MonoBehaviour {

	public GUISkin guiSkin;
	public Texture2D chestGUI;
	
	public List<inventory> chestInv = new List<inventory>();
	public List<Slot> slots = new List<Slot>();
	
	public bool drawInventory;

	void Start () {
		for(int i = 0; i < slots.Count - 1; i++){
			slots*.setupSlots();*
  •  }*
    
  • }*

  • void Update () {*

  • }*

  • void OnGUI(){*

  •  if(drawInventory){*
    
  •  	GUI.DrawTexture (new Rect((Screen.width / 2) - 128, (Screen.height / 2) - 128, 256, 256), chestGUI);*
    
  •  	for(int i = 0; i < slots.Count - 1; i++)*
    
  •  	{*
    

_ if(chestInv != null)_
* {*
GUI.DrawTexture (new Rect(slots.x, slots_.y, 32, 32), chestInv*.item.itemSprite.texture);
}
}
}
}*_

* public void giveInventory(List i){*
* this.chestInv = i;*
* }*
}

[System.Serializable]
public class Slot
{
* public int x, y;*
* public bool right, bottom;*

* public Slot(int x, int y){*
* if(right){*
* this.x = (Screen.width / 2) + x;*
* }*
* else{*
* this.x = (Screen.width /2) - x;*
* }*
* if(bottom){*
* this.y = (Screen.height / 2) + y;*
* }*
* else{*
* this.y = (Screen.height /2) - y;*
* }*
* }*
* public void setupSlots(){*
* if(right){*
* x = (Screen.width / 2) + x;*
* }*
* else{*
* x = (Screen.width /2) - x;*
* }*
* if(bottom){*
* y = (Screen.height / 2) + y;*
* }*
* else{*
* y = (Screen.height /2) - y;*
* }*
* }*
}
I know that the error is on line 29, which is this if(chestInv *!= null) but I am not sure how to fix it, I have searched for a long time but have not been able to find a solution to this.*
Any help is greatly appreciated :slight_smile:
Edit: The game runs perfectly until i press the interact key, where the GUI shows up but correctly, but that is when the error occurs causing the game to stop. Also forgot to mention that this error shows up twice!

you’re iterating using the size of slots, but checking chestInv. you need to use a separate index for chestInv, but advising how you’d do that depends on what behavior you’re trying to create.