0

I am trying to add to my Unity game the option to collect hearts that are on the map, and if the hearts health bar isn't full it will fill up accordingly. To do that, I want to take values from my HealthManager, here is part of it:

public class HealthManager : MonoBehaviour
{
    public int currentHealth;
    public int maxHealth=10;

    // Start is called before the first frame update
    void Start()
    {
        currentHealth = maxHealth;
    }
}

Now, this is from my PlayerController script:

public class PlayerController : MonoBehaviour
{
    public HealthManager healthMan;

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag=="Heart"||other.tag=="HalfHeart")
        {
            other.gameObject.SetActive(false);
            int c = healthMan.currentHealth;
            int m = healthMan.maxHealth;
        }
    }
}

When trying to pick up the hearts in the game, I get the error object reference not set to an instance of an object on the line in which I define c in PlayerController.

I can't figure out what the problem is and how to fix it.

0

1 Answer 1

1

You have a class variable in PlayerController named HealthMan, but you never set it, which is why you are getting the null reference.

1
  • just fyi it is quite usual that those are not set in code but via the Unity Inspector ;)
    – derHugo
    Commented Jul 19, 2023 at 15:09

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.