i am trying to insert an InventoryItem to my players Inventory, i used
public InventoryItem thisItem;
public void AddToInventory()
{
int itemIndex = pInv.inventory.IndexOf(thisItem);
pInv.inventory.Insert(itemIndex, thisItem);
Debug.Log(itemIndex);
Debug.Log(thisItem.name);
Destroy(gameObject);
}
to firstly, find the first open slot in the list, then i used insert to insert the inventory item to that index, and then i destroyed the game object last. Even after referencing the inventory item in the inspector it still comes out as a null reference exception. Any help? if in need of more information just say so. Thanks.
This process is the same for every null reference exception. It’s similar for all debugging. The console will tell you what line of code had the exception.
You just have to go through all of the objects on that line of code (or sometimes one line above or following) to decide if they might possibly be null. You can use Debug.Log() to print out information to the console. You can use Assert.IsTrue() to check your assumptions as you design code. You can single-step through code as it executes if you attach a debugger. Find out what is null. Code defensively to avoid using object references that might be null.
Line 4: if pInv is null, it will crash trying to get pInv.inventory.
Line 4: if pInv.inventory is null, it will crash trying to call pInv.inventory.IndexOf().
Line 6: you already got past line 4, and no changes to these, so those probably are good
Line 8: if thisItem is null, it will crash trying to get thisItem.name.