Hi there, I’m getting the above error, the object reference is not set to an instance of an object, and I seriously cannot find the reason for it. Here, I’ll break it down.
I have my main character script trying to access an inventory script in the Start() function:
Inventory inventory;
GameObject InventoryGUI;
//Start()...
InventoryGUI = GameObject.FindGameObjectWithTag("Inventory GUI");
inventory = InventoryGUI.GetComponent<Inventory>();
Later in the script I try to call the PickUpItem() function from the inventory script:
if (Input.GetKeyDown(KeyCode.F))
{
Ray ray = playerCam.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
RaycastHit hitinfo;
Debug.DrawRay(ray.origin, ray.direction * 2, Color.yellow);
if (Physics.Raycast(ray, out hitinfo, 2f))
{
if (hitinfo.collider.gameObject.tag == "Inventory Item")
{
//Here be the issue
inventory.PickUpItem(hitinfo.collider.gameObject.name);
Debug.Log("Hit! " + hitinfo.collider.gameObject.name);
}
}
}
Never mind the raycasts, the Debug.log shows that they work. The only issue is when I call the PickUpItem() function, or try to access variables from the Inventory script, for that matter (I tried Debug.log on an inventory variable, same issue). That is where the null reference exception happens.
Here is the function I’m trying to call:
public void PickUpItem(string newItemName)
{
inventoryItems[invNumberOfItems] = GameObject.Find(newItemName).GetComponent<InventoryItem>();
invNumberOfItems++;
}
The InventoryItem component is just a class attached to each specific item with variables of data like a name an description. I can’t test to see if that function even works because the code doesn’t get that far.
The Inventory script is attached to a GUIText object (Later to be upgraded to a GUITexture) and all the tags n stuff are correct. I’m stumped… I… I just can’t find where I went wrong.
Help pls. =(