0

enter image description here I made this class of the players health and set a public int varible for the health

enter image description here When I try to edit the value in another class it does not edit so I added a Debug.Log statement to check if class is null (Sorry I didnt realise that the reference to class and the health inside the class are same it looks messy)

enter image description here Over here it is saying class is null, I searched all over google and youtube for the error and I could not find anything of the class being null is there a possible fix???

Max Play
  • 3,717
  • 1
  • 22
  • 39
Socket
  • 1
  • 1
  • 4
    You need to post code in the question with formatting. Where is the PlayerHealth class is instantiated. Since it is a derived class of MonoBehavior, you need to make an empty gameobject and add the PlayerHealth script as a component of that. And assign it to the public variable health in your L1ZombieNavigationHandler class. – mmj Aug 14 '22 at 09:21
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Max Play Aug 14 '22 at 09:35
  • I already added it to a GameObject but it still is not working – Socket Aug 14 '22 at 09:58
  • In your 2nd screenshot I can see that you have a _guard_ that tests for `null` but it is **incomplete**. All you are currently doing is displaying a log entry. Typically guards return a error or throw an exception. Consider changing `Debug.Log()` to `Debug.LogError()` **and** add a `return` statement. No point testing for `null` if you are only going to use it in the next line! (hence the exception you are running into) –  Aug 14 '22 at 10:04
  • You checked if it was null and it indeed did that. But you did not set the rest of the code to change the value in an else so despite being null it’s still doing it. A very basic issue – BugFinder Aug 14 '22 at 10:10

1 Answers1

0

You can drag and drop a reference to the PlayerHealth component using the Inspector of your other component by making your health variable a serialized field.

[SerializeField]
private PlayerHealth health; // assign reference in the Inspector

private void GiveDamageToPlayer()
{

Alternatively you can use GetComponent to assign the reference at runtime using code.

private PlayerHealth health;

private void Awake() => health = GetComponent<PlayerHealth>(); // assign reference in code

private void GiveDamageToPlayer()
{
Sisus
  • 651
  • 4
  • 8