NullReferenceException on health pickup script [Fixed!!]

I’m battling to get my health pickup to work. I have a script for health and a script for health pickups, but I cannot get the pickup to add to my current health. I get the error message:

NullReferenceException: Object reference not set to an instance of an object
LHPickupHeal.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Pickups/LHPickupHeal.cs:22)

I’ve searched, but not had any luck in fixing the problem. If I take out the line in question, the object disappears as it should, but adds no health of course. Any advice on how to fix my pickup script so it works? I realise it might be easier to put the pickup in the health script, but I have a number of pickups of which health is just one, which is why I have split it out.

Scripts below:

HEALTH SCRIPT
```csharp
*using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class LHPCHealth : MonoBehaviour
{

    public int maxHealth = 100;            //PC max health
    public int curHealth = 100;            //PC current health
    bool isDead = false;                     //Bool if PC is dead
    public Slider healthSlider;             // Reference to the UI's health bar.
    LHPCMovement pcMovement;     // Reference to the player's movement.
    LHPCAttack pcAttack;                // Reference to the LHPCAttack script.

    void Awake ()
    {
            pcMovement = GetComponent<LHPCMovement> ();
            pcAttack = GetComponent<LHPCAttack> ();
    }

    void Start ()
    {
            curHealth = maxHealth;
    }

    void Update ()
    {
            healthSlider.value = curHealth;
            if (curHealth <= 0 && !isDead) {
                    Death ();
            }
    }

    public void AddHealth (int amount)
    {
            curHealth += amount;
            if (curHealth <= 0) {
                    curHealth = 0;
            }
       
            if (curHealth >= maxHealth) {
                    curHealth = maxHealth;
            }
    }

    public void TakeDamage (int amount)
    {
            curHealth -= amount;
    }

    void Death ()
    {
            isDead = true;               
            pcMovement.enabled = false;
            pcAttack.enabled = false;
            LHPCDead.show ();
            Application.LoadLevel ("TavernBedroom");
    }

}*
* _**PICKUP SCRIPT**_ *csharp
*using UnityEngine;
using System.Collections;

public class LHPickupHeal : MonoBehaviour
{
public AudioClip healGrab; // Audioclip to play when the heal is picked up
public int healPoints; //Amount to heal
LHPCHealth lhPCHealth; //Reference to PC health script
GameObject player; // Reference to the player.

    void Awake ()
    {
            player = GameObject.FindGameObjectWithTag ("Player");
            lhPCHealth = GetComponent<LHPCHealth> ();
    }

    void OnTriggerEnter (Collider other)
    {
            if (other.gameObject == player) {
                    AudioSource.PlayClipAtPoint (healGrab, transform.position);
                    lhPCHealth.AddHealth (healPoints);           / <----------error here!
                    Destroy (gameObject);
            }
    }

}*
```

I looks like lhPCHealth is not attached to your game object, so your provably getting null when you call:

lhPCHealth = GetComponent<LHPCHealth> ();

LHPCHealth is definitely attached to the player character and on line 22 of the pickup script, intellisense picks up the AddHealth function without a problem. All seems good when creating the script, but when in game mode…not so much. Is there another way to force it to get the health script from the player instance apart from setting the references for both player and lhPCHealth in Awake? Or should I use Start instead? Sorry, brain has gone all moggy in trying to find the problem :frowning:

Intellisense is a tool that provides you with options when you write code; it does not tell you whether a reference is null.

The error that you got occurs when you try to use an object that has not been defined. Your script could be there but lhPCHealth is not pointing to it. Maybe Unity is calling OnTriggerEnter before Awake. Instead of using Awake try using OnEnable, this function gets called when the objects is loaded.

You could also create a property that updates its reference if the reference is null:

private LHPCHealth lhPCHealth
{
    get{ return _lhPCHealth??(_lhPCHealth = GetComponent<LHPCHealth>()); }
}
private LHPCHealth _lhPCHealth

This property will only return null if unity cannot find LHPCHealth when calling GetComponent.

From the looks of your scripts, LHPCHealth is located on the player character GameObject and LHPickupHeal is on a different GameObject that the character can interact with.

The version of GetComponent that you’re using wont work because you’re trying to get the player’s health from the pickup GameObject as opposed to the player.

You probably meant to do something like this:

                player = GameObject.FindGameObjectWithTag ("Player");
                lhPCHealth = player.GetComponent<LHPCHealth> ();

This way, you’re explicitly stating what GameObject you want to get the component from.

@RSG : I am beginning to think that I will have to restructure my approach on my health script. You are right and it does not find LHPCHealth and the function (Addhealth) to execute the trigger event of adding health. I set a public bool on LHPCHealth and changed the health pickup script to just change the bool. It fails with the same error. What is odd is that my keypickup script (structured the same way) has no such issues. Will play around a bit more, but in the meantime, if you see anything wrong with LHPCHealth, please let me know. And thank you for the assistance so far! I am sure it is something silly, but I am just not seeing the source of the problem - but at least now understand that it seems to lie with my health script and not the health pickup!

@Stoven : Interesting! Will try quick before I start tearing up my health script. You are correct that LHPCHealth is on my player char and LHPickupHeal is on the healing prefab.

OMW!!! Stoven! You found my problem :slight_smile:
Thank you both for helping me on the right track to fix this problem. VERY much appreciated!

…What does OMW mean? I think I know, but…

Oh my word :slight_smile: