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);
}
}
}*
```