I understand that the currentHealt variable is not set to correct Object, or something like that, but I don’t understand how is that possible.
I even copied the code from the tutorial page, so there aren’t any typos. Player has “Player tag”
and “Default Layer”. Zombunny has “Untagged tag” and “Shootable layer”.
I tried to debug the problem, with my limited abilities.
player = GameObject.FindGameObjectWithTag (“Player”);
this returns Player, so the correct object.
playerHealth = player.GetComponent ();
and this returns nothing. So the player variable references to correct Player object, which has the PlayerHealth script (with correct name PlayerHealth). This script has public class PlayerHealth, with public variable currentHealth, which changes in public method (or is it just a funciton in C#?) TakeDamage. Yet it doesn’t return the value of currentHealth from Player object.
I really don’t understand what’s wrong and any help would be greatly appreciated. Thank you in advance.
I ran into the same error, and the problem in my case was that there was another object in my hierarchy tagged “Player”. Specifically, the top level player object has a child also named “Player”, and somehow both ended up tagged.
Since the PlayerHealth script is attached only to the parent, the line
The playerHealth variable doesn’t actually contain the player’s health as a number. It’s a reference to the PlayerHealth component attached to the player. When you need to see the player’s health, you would use playerHealth.currentHealth - this is like asking the PlayerHealth component for its currentHealth variable, which is an integer containing the player’s health as a number.
There seems to be a problem with scope or something. The EnemyAttack public class has access to Player object, but has no access to PlayerHealth public class, therefore, it cannot access the currentHealth variable.
At least that’s my limited understanding of the problem.