Health variable not changing
I've seen a million people ask this but i still haven't found a fix.
So, since i'm really new to Unity and C# in general, i wanted to try to make a simple health and damage system, but it doesn't work because my health variable refuses to change.
On my player i have attached two scripts, HealthBehaviour
and PlayerController
. In my player controller, i have movement and also a test key for damaging the player:
https://pastebin.com/tE8nWM7t
And this is my health system:
https://pastebin.com/7Z1U1BX4
I've already tried multiple things.
In the example above (first thing i tried), i had the variable as public and changed it in the inspector.
Second attempt, i changed it to:
[System.NonSerialized] public int health = 20;
And it still didn't change upon damage.
What am i doing wrong? Thanks!
Answer by kensct · Aug 09, 2021 at 09:56 PM
var health = rb.gameObject.GetComponent<HealthBehaviour>().health;
health = health - damage;
Needs to be
var healthBehaviour = rb.gameObject.GetComponent<HealthBehaviour>();
healthBehaviour.health -= damage;
The reason this was not working is because .heath is an int which is a struct not a class. This means you don't have a reference to heath instead you have a copy so you are only changing a copy.
If instead you get the HealthBehaviour as this is a class you get the reference to that class and can change values on it.
Also I recommend not using var and instead using the class name as var makes it harder to read, but this is personal preference.