NullReferenceException: Object reference not set to an Instsance of an object

Trying to make a “Health Injection” too.
I have connected the script to the object.
Here’s the code for the HealthInjection script;

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class HealthInjection : MonoBehaviour

{

[SerializeField] float healthIncrease = 20f;

void OnTriggerEnter(Collider other)

{

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

    {

        IncreaseHealth();

        Destroy(gameObject);

    }

}

void IncreaseHealth()

{

    healthIncrease = GetComponent<PlayerHealth>().hitPoints += healthIncrease;

}

}

and the PlayerHealth script;

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using TMPro;

public class PlayerHealth : MonoBehaviour

{

[SerializeField] public float hitPoints = 100f;

[SerializeField] TextMeshProUGUI healthText;

void Update()

{

    healthText.text = "Health:" + hitPoints.ToString() + "%";

}



public void TakeDamage(float damage)

{

    hitPoints -= damage;

    if (hitPoints <= 0)

    {

        GetComponent<DeathHandler>().HandleDeath();

    }

}

}

Hi,

NullReferenceException means that a reference (“link”) to an instance is missing. Double click on the error message to see to which line in your code it is referring. If you exposed a field in the Inspector, make sure that it’s not empty.


See also:

Ok. Thanks!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms