NullReferenceException: Object reference not set to an instance of an object EnergyPickup.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Objects/EnergyPickup.cs:20)

Hello guys,

I am having a hard time solving this issue.
I keep getting the error below:
NullReferenceException: Object reference not set to an instance of an object
EnergyPickup.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Objects/EnergyPickup.cs:20)

I have two scripts: Energy Pickup and Player Inventory

using UnityEngine;
using System.Collections;

public class EnergyPickup : MonoBehaviour 
{
	private PlayerInventory playerInventory;

	void Start()
	{
		playerInventory = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerInventory>();
	}

	void OnTriggerEnter(Collider other)
	{

		if(other.tag == "Player")
		{

			playerInventory.collectedEnergy++;
			gameObject.SetActive(false);

		}
	}
}

And the second one

using UnityEngine;
using System.Collections;


public class PlayerInventory : MonoBehaviour 
{
	public int collectedEnergy = 0;

	// Use this for initialization
	void Start () 
	{
		
	}
	
	// Update is called once per frame
	void Update () 
	{
		
	}
}

For some reason every time I enter with the player in the trigger point I get error and it is not counting +1

What do you guys think?

I think your PlayerInventory didn’t exist on a game object tagged “Player”.

 void OnTriggerEnter(Collider other)
 {
     if(other.tag == "Player")
     {
         playerInventory.collectedEnergy++; // playerInventory is null
         gameObject.SetActive(false);
     }
 }

Why is it null?

playerInventory = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerInventory>();

Either you didn’t have the PlayerInventory component on all objects with the tag “Player”, or the object tagged Player was inactive or didn’t exist. If the object tagged Player didn’t exist or was inactive, you should have seen an exception in the log. If you didn’t see an exception in the log, chances are you forgot to add the inventory to your player, or that you have multiple objects tagged player and the object that happened to be returned from FindGameObjectWithTag, had no inventory component.

Or, the script was there, but later destroyed.

In short: Make sure you have one game object tagged Player, make sure it is active and make sure it has a PlayerInventory component. If you have multiple game objects tagged Player, then consider what makes most sense for you. Should all of them be tagged Player? Should you rely on a mechanism that give you “any” game object tagged player?