Need some help with a NullReference Error

Hi, I am getting a NullReference Error in my script here:

import System.Collections.Generic;
enum State{open, close, inbetween}
var openSound : AudioClip;
var closeSound : AudioClip;

var parts : GameObject[];
var defaultColors : Color[];
var particleEffect : GameObject;
var go : GameObject;
var maxDistance : float;
var player : GameObject;
var mytransform : Transform;
var inUse = false;
var MyGUI;
var chest;
var used = false; //track if the chest has been used or not
var x : int;
var Chest : Chest;

var cnt : int;
var glow : boolean;
var state : State;

var loot : List.<Item>;
var ItemGenerator : ItemGenerator;
//[RequireComponent(typeof(BoxCollider))]
//[RequireComponent(typeof(AudioSource))]

//public State state;
function Start() {
MyGUI = GameObject.Find("GUIElements").GetComponent("MyGUI");
chest = GameObject.Find("GUIElements").GetComponent("MyGUI").chest;
loot = new List.<Item>();
mytransform = transform;
state = Chest.State.close; <<ERROR OCCURS HERE

particleEffect.active = false;

defaultColors = new Color[parts.Length];

if(parts.Length > 0)
for(cnt = 0; cnt < defaultColors.Length; cnt++)
defaultColors[cnt] = parts[cnt].renderer.material.GetColor("_Color");
}

function Update () {
if(!inUse)
return;

if(player == null)
return;

if(Vector3.Distance(mytransform.position, player.transform.position) > maxDistance && !inUse)
MyGUI.chest.ForceClose();
//SendMessageUpwards("CloseChest");
}

function OnMouseEnter() {
Debug.Log("Enter");
HighLight();
}

function OnMouseExit() {
HighLight();
}

function OnMouseUp() {
go = GameObject.FindGameObjectWithTag("Player");
if(go == null)
return;

if(Vector3.Distance(transform.position, go.transform.position) > maxDistance)
return;
}

switch (state) {
case State.open:
	state = Chest.State.inbetween; <<<ERROR OCCURS HERE
	//StartCoroutine("Close");
	ForceClose();
break;

case State.close:
	if(GameObject.Find("GUIElements").GetComponent("MyGUI").chest != null) {
	GameObject.Find("GUIElements").GetComponent("MyGUI").chest.ForceClose();
	}
	state = Chest.State.inbetween; <<<ERROR OCCURS HERE
	StartCoroutine("Open");
	Debug.Log("CHEST OPENED!!");
break;

}
//if(state == Chest.State.close)
//Open();
//else
//Close();

function Open() {
MyGUI.chest = this;
player = GameObject.FindGameObjectWithTag("Player");
inUse = true;
//animation.Play("");
particleEffect.active = true;
//AudioClip.Play("openSound");
if(!used)
PopulateChest();//5
//yield return new WaitForSeconds(2);

state = Chest.State.open; <<<ERROR OCCURS HERE
//SendMessageUpwards("PopulateChest", 5); //gameObject
SendMessageUpwards("DisplayLoot"); //gameObject

}

function PopulateChest() {
//chest = go;
for(cnt = 0; cnt < x; cnt++) { //x
loot.Add(ItemGenerator.CreateItem());
//loot[cnt].Name = "I:" + Random.Range(0, 100);
used = true;
}

}

function Close() {
player = null;
inUse = false;
//SendMessageUpwards.DONT_REQUIRE_LISTENER("PopulateChest", 5);

//animation.Play("");

particleEffect.active = false;
//AudioClip.Play("closeSound");
//yield return new WaitForSeconds(2);

state = Chest.State.close; <<<ERROR OCCURS HERE

if(loot.Count == 0)
Destroy(gameObject);
}

function ForceClose() {
SendMessageUpwards("CloseChest");

StopCoroutine("Open");
StartCoroutine("Close");
}

function HighLight() {
if(glow) {
if(parts.Length > 0)
for(cnt = 0; cnt < defaultColors.Length; cnt++)
parts[cnt].renderer.material.SetColor("_Color", Color.yellow);
}

else {
if(parts.Length > 0)
for(cnt = 0; cnt < defaultColors.Length; cnt++)
parts[cnt].renderer.material.SetColor("_Color", defaultColors[cnt]);
}
}

I marked all the lines where the error is occuring. Basically it throws me the error every time I call the variable ‘state’ to equal something. Can someone take a quick look and see what I’m doing wrong? Thanks!

It looks to me like it is not finding a value for Chest. The error is probably originating from this line chest = GameObject.Find("GUIElements").GetComponent("MyGUI").chest;

Is the “MyGUI” properly attached to your “GUIElements”?

Just gonna go ahead and post my MyGUI script as well in case it helps:

MyGUI.js

import System.Collections.Generic;
var Loot_Window_ID : int = 0;
var lootWindowRect : Rect = new Rect(0,0,0,0);
var offset : float = 10.0;
var lootWindowHeight : float = 90;
var buttonWidth : float = 40;
var buttonHeight : float = 40;
//var lootItems : List.<Inventory>;
var lootWindowSlider : Vector2 = Vector2.zero;
var displayLootWindow = false;
var cnt : int = 0;
var cnt1 : int = 0;
var closeButtonWidth : float = 20;
var closeButtonHeight : float = 20;
var x : int;
var y : int;
static var chest : Chest;
var go : GameObject;
var _toolTip = "";
var mySkin : GUISkin;
var u;

var displayInventoryWindow = true;
var Inventory_Window_ID : int = 1;
var inventoryWindowRect : Rect = new Rect(10,10,170,265);
var inventoryRows : int = 6;
var inventoryCols : int = 4;
var doubleClickTimer : float = 0;
var Double_Click_Timer_Threshold : float = .5f;
var selectedItem; //Item
var EquippedWeapon;
var inventory;

var displayCharacterWindow = true;
var Character_Window_ID : int = 2;
var characterWindowRect : Rect = new Rect(10,10,170,265);
var characterPanel : int = 0;
var characterPanelNames : String[];

var Inventory;
//var InventoryWindowSlider : Vector2 = Vector2.zero;

function Start() {
Inventory = GameObject.Find("GUIElements").GetComponent("Inventory");
EquippedWeapon = GameObject.Find("GUIElements").GetComponent("Inventory").EquippedWeapon;
inventory = GameObject.Find("GUIElements").GetComponent("Inventory").inventory;

characterPanelNames = new String[3];
characterPanelNames[0] = "Equipment";
characterPanelNames[1] = "Attributes";
characterPanelNames[2] = "Skills";

//lootItems = new List.<Inventory>();
//PopulateChest();
}

function OnEnable() {
//SendMessageUpwards.AddListener("PopulateChest", PopulateChest);
SendMessageUpwards.AddListener("DisplayLoot", DisplayLoot);
SendMessageUpwards.AddListener("CloseChest", CloseWindow);
SendMessageUpwards.AddListener("ToggleInventory", ToggleInventoryWindow);

}

function OnDisable() {
//SendMessageUpwards.RemoveListener("PopulateChest", PopulateChest);
SendMessageUpwards.RemoveListener("DisplayLoot", DisplayLoot);
SendMessageUpwards.RemoveListener("CloseChest", CloseWindow);
SendMessageUpwards.RemoveListener("ToggleInventory", ToggleInventoryWindow);


}

function Update () {
}

function OnGUI() {
GUI.skin = mySkin;

if(displayInventoryWindow)
inventoryWindowRect = GUI.Window(Inventory_Window_ID, inventoryWindowRect, InventoryWindow, "Inventory");

if(displayCharacterWindow)
characterWindowRect = GUI.Window(Character_Window_ID, characterWindowRect, CharacterWindow, "Character");

if(displayLootWindow)
lootWindowRect = GUI.Window(Loot_Window_ID, new Rect(offset, Screen.height - (offset + lootWindowHeight), Screen.width - (offset * 2), lootWindowHeight), LewtWindow, "LootWindow");

DisplayToolTip();
}
 
function LewtWindow() {
GUI.skin = mySkin;

if(GUI.Button(new Rect(lootWindowRect.width - 20, 0, closeButtonWidth, closeButtonHeight), "x")) 
CloseWindow();

if(chest == null)
return;

if(chest.loot.Count == 0){
CloseWindow();
return;
}

lootWindowSlider = GUI.BeginScrollView(new Rect(offset * .5f, 15, lootWindowRect.width - 10, 70), lootWindowSlider, new Rect(0,0, (chest.loot.Count * buttonWidth) + offset, buttonHeight + offset));

for(cnt = 0; cnt < chest.loot.Count; cnt++) {
if(GUI.Button(new Rect(5 * .5f + (buttonWidth * cnt), offset, buttonWidth, buttonHeight), new GUIContent(chest.loot[cnt].ToolTip(), chest.loot[cnt].Icon,"Inventory Slot Common"))) { 
Debug.Log(chest.loot[cnt].ToolTip());
Inventory.inventory.Add(chest.loot[cnt]);//1
chest.loot.RemoveAt(cnt);
}

}
GUI.EndScrollView();

SetToolTip();
}

function DisplayLoot() {
displayLootWindow = true;
}

//function PopulateChest() {
//chest = go;
//for(cnt = 0; cnt < 2; cnt++)
//lootItems.Add(new Inventory());
//displayLootWindow = true;
//}

function CloseWindow() {
//lootItems.Clear();
chest.OnMouseUp();
chest = null;
displayLootWindow = false;
}

function InventoryWindow() {

for(y = 0; y < inventoryRows; y++) {
for(x = 0; x < inventoryCols; x++) {
if(cnt < GameObject.Find("GUIElements").GetComponent("Inventory").inventory.Count) {//1
if(GUI.Button(new Rect(5 + (x * buttonWidth), 20 + (y * buttonHeight), buttonWidth, buttonHeight), new GUIContent(Inventory.inventory[cnt].ToolTip(), Inventory.inventory[cnt].Icon, "Inventory Slot Common"))); 
if(doubleClickTimer != 0 && selectedItem != null) {
if(Time.time - doubleClickTimer < Double_Click_Timer_Threshold) {
Debug.Log("Double Click" + Inventory.inventory[cnt].Name);

if(Inventory.EquippedWeapon == null){
Inventory.EquippedWeapon = Inventory.inventory[cnt];
Inventory.inventory.RemoveAt(cnt);
}
else {
var temp = Inventory.EquippedWeapon; //Item
Inventory.EquippedWeapon = Inventory.inventory[cnt];
Inventory.inventory[cnt] = temp;
}

doubleClickTimer = 0;
selectedItem = null;
}
else {
Debug.Log("Reset the double click timer");
doubleClickTimer = Time.time;
}
}
else{
doubleClickTimer = Time.time;
selectedItem = Inventory.inventory[cnt];
} 
}                                                                                               
else {
GUI.Label(new Rect(5 + (x * buttonWidth), 33 + (y * buttonHeight), buttonWidth, buttonHeight), (x * y * inventoryCols).ToString(), "Inventory Slot Empty");
}
//cnt++;//1
SetToolTip();
GUI.DragWindow();
}
}
}


function ToggleInventoryWindow() {
displayInventoryWindow = !displayInventoryWindow;
}

function CharacterWindow() {
characterPanel = GUI.Toolbar(new Rect(5, 25, characterWindowRect.width - 10, 50), characterPanel, characterPanelNames);

switch(characterPanel) {
case 0:
	DisplayEquipment();
	break;
	
case 1:
	DisplayAttributes();
	break;
	
case 2:
	DisplaySkills();
	break;

}

GUI.DragWindow();
}

function DisplayEquipment() {
//Debug.Log("Displaying Equipment");
if(GameObject.Find("GUIElements").GetComponent("Inventory").EquippedWeapon == null) {
GUI.Label(new Rect(5, 100, 40, 40), "X");
}
else {
GUI.Button(new Rect(5, 100, 40, 40),Inventory.EquippedWeapon.Icon);
}
}

function DisplayAttributes() {
//Debug.Log("Displaying Attributes");
}

function DisplaySkills() {
//Debug.Log("Displaying Skills");
}

function SetToolTip() {
if(Event.current.type == EventType.Repaint && GUI.tooltip != _toolTip) {
if(_toolTip != "")
_toolTip = "";

if(GUI.tooltip != "")
_toolTip = GUI.tooltip;
}
}

function DisplayToolTip() {
if(_toolTip != "")
GUI.Box(new Rect(Screen.width / 2 - 100, 10, 200, 100), _toolTip);

}

I had a reflexion about it earlied but I had a hard time explaining my thought, I'll give it another try. So this script is Chest.js , making it the Chest : MonoBehaviour class.

I assume you want one or multiple instances of Chest which all manage their own state variable holding a State enum value. Wheelandrew talked about chest, but the problem is Chest.

You could maybe add `Chest = this;` as the first line of the Start() function or (choose this:) remove all references to Chest, as they are totally unnecessary and make it harder to read. Rewrite it as state = State.close; and remove the Chest variable.