I’ve been running into this exception all night, also randomly my code will work and will stop working. I think it has something to do with declaring variables in monodevelop and manipulating them in unity, or maybe scripting order, as this is based off of a previous script and I may have copied and pasted. Does anyone have any thoughts on this, why I get the exception or why the code is so fickle?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Test : MonoBehaviour {
private bool showGUI;
public GUISkin skin;
private int itemMenuPositionX = Screen.width / 3;
private int equipMenuPositionX = (Screen.width / 3) * 2;
private ItemDatabase itemDatabase;
private Rect itemList;
private Rect item;
private List<Item> inventory = new List<Item>();
private List<Item> slots = new List<Item>();
private Vector2 scrollPosition = Vector2.zero;
public int inventorySize = 5;
// Use this for initialization
void Start () {
for(int i = 0; i < inventorySize; i++)
{
slots.Add (new Item());
inventory.Add(new Item());
}
itemDatabase = GameObject.FindGameObjectWithTag("Item Database").GetComponent<ItemDatabase>();
AddItem(1);
AddItem(0);
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.A))
{
showGUI = !showGUI;
}
}
void OnGUI()
{
if(showGUI)
{
Rect itemList = new Rect(0,0, Screen.width / 3, Screen.height);
Rect item = new Rect(itemMenuPositionX, 0, Screen.width / 3, Screen.height);
Rect equip = new Rect(equipMenuPositionX, 0, Screen.width / 3, Screen.height);
GUI.Box (itemList, "Inventory", skin.GetStyle("Tooltip"));
GUI.Box (item, "Item", skin.GetStyle("Tooltip"));
GUI.Box (equip, "Equip", skin.GetStyle("Tooltip"));
scrollPosition = GUI.BeginScrollView(itemList, scrollPosition, itemList);
for (int i = 0; i < slots.Count; i++)
{
slots[i] = inventory[i];
Rect slotRect = new Rect(0 , i * 25, Screen.width / 3, 25);
GUI.Box (slotRect, slots[i].itemName, skin.GetStyle("Slot"));
}
GUI.EndScrollView();
}
}
void RemoveItem(int id)
{
for(int i = 0; i < inventory.Count; i ++)
{
if(inventory[i].itemID == id)
{
inventory[i] = new Item();
break;
}
}
}
void AddItem(int id)
{
Debug.Log("Help6");
for(int i = 0; i < inventory.Count; i++)
{
Debug.Log("Help5");
if(inventory[i].itemName == null)
{
Debug.Log("Help4");
for (int j = 0; j < itemDatabase.items.Count; j++)
{
Debug.Log("Help3");
if(itemDatabase.items[j].itemID == id)
{
Debug.Log("Help2");
inventory[i] = itemDatabase.items[j];
Debug.Log("Help1");
}
}
break;
}
}
}
bool InventoryContains(int id)
{
bool result = false;
for(int i = 0; i < inventory.Count; i++)
{
result = inventory[i].itemID == id;
if(result)
{
break;
}
}
return result;
}
}