- Home /
Why the null reference?
Hello, I get a null reference exception in the following code:
the variable "itemInstance" is of class Item, soil inherits from Item.
However, when the code goes to check soil.contents[0] (a member of the inherited class) I get the error.
if(isInitialized == false){
soil = itemInstance as Soil;
isInitialized = true;
}
if( soil.contents[0] != null ){ //<<---- NULL REFERENCE EXCEPTION HERE
Seed seed = new Seed();
seed = (Seed)soil.contents[0];
soilState = SoilState.fertile;
}
Thanks!
EDIT: I should add that itemInstance is declared as an Item but a Soil was put in to it.
Answer by jdyeager · Nov 04, 2013 at 04:07 PM
There are a few possibilities that I see:
itemInstance is null
isInitialized is true already (so soil never gets set)
Soil is not a sub-class of Item
soil.contents is null instead of an array of Seeds
Also, just a quick tip, you don't need to do:
if (isInitialized == false) { ... }
Since isInitialized is a boolean already you can just do:
if (!isInitialized) { ... }
I think issue here is described at this link.
I'm starting to learn more what the problem is; as I'm learning the proper names for everything I can figure how to Google it better.
I checked,
itemInstance isn't null, I can debug.Log its name.
isInitialized starts as false, thats how I declared it
Soil inherits from Container, Container inherits from Item
Soil soil = itemInstance; itemInstance is set as this GameObject is created in the following scripts:
void Drop$$anonymous$$ouseItem(){ if(playerInventory.mouseItem != null){ if(Input.Get$$anonymous$$ouseButtonUp(0) && !mouseBusy){ mouseBusy = true; Vector3 dropPos = this.transform.TransformPoint( Vector3.forward * dropDistance ); dropPos = new Vector3(dropPos.x, dropPos.y + 1, dropPos.z); spawn.Item(playerInventory.mouseItem, dropPos); playerInventory.mouseItem = null; } } }
public GameObject Item(Item newItem, Vector3 position){ GameObject go = Instantiate(Resources.Load("Item/" + newItem.prefabName), position, Quaternion.identity) as GameObject; go.AddComponent(); BoxCollider bc = go.AddComponent(); ItemBehaviour ib = go.AddComponent(); ib.itemInstance = newItem; return go; }
Answer by Cains · Nov 04, 2013 at 04:10 PM
I'm not sure when this portion of the code runs in your project, but if it checks soil.contents[0] before you set soil equal to something it'll throw that error.
If it's not that I think it may be something in itemInstance, perhaps your contents array isn't being declared/populated or it just doesn't exist.
It should exist. I have the following line in the constructor.
contents = new Item[1];
However, I'm concerned it gets snipped in the process of being saved as an Item for 1 step of the way, but the way my code works I'm not sure how to bypass that step. See the link I linked jdyeager. I'm trying to figure out if that is the problem.