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 ObviouslyInsane · Jan 12, 2012 at 01:45 AM · errorenumnullreference

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!

Comment
Add comment · Show 5
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 by0log1c · Jan 12, 2012 at 02:11 AM 1
Share

I didn't expect the line var Chest:Chest; to compile. Especially not with #pragma strict. Is it just me or unless the class Chest was static, you'll never know what Chest returns?

avatar image syclamoth · Jan 12, 2012 at 03:36 AM 0
Share

Can you tell us what line the error occurs on? That's a long script, and I can't easily analyse all of it at once.

avatar image ObviouslyInsane · Jan 12, 2012 at 03:41 AM 0
Share

I marked all the lines the error occurs on with '<<

avatar image syclamoth · Jan 12, 2012 at 03:59 AM 1
Share

I see. Well, it's basically what @BY0LOG1C says- you shouldn't give an object the same name as its class (or for that matter, any class! It's why it's usually the standard to give variables lower-case names, and capitalise class-names)

avatar image ObviouslyInsane · Jan 12, 2012 at 04:14 AM 0
Share

Thanks for the tip. I changed the variable name but still having the same errors. Any other ideas?

3 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by by0log1c · Jan 12, 2012 at 04:08 AM

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.

Comment
Add comment · Show 1 · 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 ObviouslyInsane · Jan 12, 2012 at 04:41 AM 0
Share

Fantastic, that fixed it. Thank you so much guys and to BY0LOG1C for explaining in such detail.

avatar image
0

Answer by Whelandrew · Jan 12, 2012 at 02:01 AM

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"?

Comment
Add comment · Show 1 · 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 ObviouslyInsane · Jan 12, 2012 at 03:27 AM 0
Share

It is properly attached, and I probably should have mentioned the script I posted is the Chest.js script.

avatar image
0

Answer by ObviouslyInsane · Jan 12, 2012 at 03:32 AM

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);
 
 }
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

7 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

access enum values 0 Answers

Shop system using Enum throws up errors. 0 Answers

C# Edit enum values in inspector 1 Answer

Hashtable.Enumerator: snapshot out of sync 1 Answer

Enum switch statement error 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