- Home /
Null reference exception
I have a peace of code that gives me a null reference error untill I either compile or click on the gameobject that the component is attached to.
Code:
var InvI : int[] = new int[Inventory.Length];
var InvA : int[] = new int[Inventory.Length];
var InvS : int[] = new int[Inventory.Length];
for (var i = 0; i < Inventory.Length; i++) {
if (Inventory[i] == null){
Debug.Log("Inventory slot: #"+i+" is null"); //This prints every frame.
}
InvI[i] = Inventory[i].ID; //This line gives me a null reference error
InvA[i] = Inventory[i].Amount;
InvS[i] = Inventory[i].Slot;
}
The problem is that the Inventory[i] is null, but Inventory isn't null.
Does null mean that it is the basic value for example a null string would be ""?
Answer by KurtGokhan · Jan 12, 2015 at 04:44 PM
Are you assigning any objects to Inventory? It appears Inventory is an array of a class object. Class objects must be instantiated or you will get null reference error. To assign all slots in array:
for(int i=0; i < Inventory.Length; i++){
Inventory[i] = new SomeClass();
}
So this would do it right:
var InvI : int[] = new int[Inventory.Length];
var InvA : int[] = new int[Inventory.Length];
var InvS : int[] = new int[Inventory.Length];
for (var i = 0; i < Inventory.Length; i++) {
if (Inventory[i] != null){
Inventory[i] = new Game.inventorySlot();
}
InvI[i] = Inventory[i].ID;
InvA[i] = Inventory[i].Amount;
InvS[i] = Inventory[i].Slot;
}
Yes that should do it. But I cannot see what you want to achieve here. If Id, Amount and Slot is assigned in constructor than should be ok. But I feel like you are trying to achieve a reference to inventory id slot and amount. Note that int is not reference type but value type so you cannot have reference like this. Anyways I don't know your code's internals so ignore me if I am getting this wrong.
I'm trying to convert it into int[]'s so that I can sync them over the network and then assemble them again on the other side :)
Your answer
Follow this Question
Related Questions
SplatMap error 1 Answer
avoid null when multiple classes are modifying the same thing 2 Answers
List<> and Crafting null reference. 1 Answer
Unity null check 1 Answer
Inventory problem. 1 Answer