Hey all. I want to change the variable “currentHealth” without result. “takeDamage” changes as the public static int variable “ExternalScript.damage” is accessible from another script. It must be something simple but i fail to see it. Any enlightenment is appreciated!
public class Enemy : MonoBehaviour
{
public int maxHealth = 10;
public int currentHealth;
public int takeDamage;
void Start()
{
currentHealth = maxHealth;
}
void Update()
{
takeDamage = ExternalScript.damage;
}
public void TakeDamage()
{
currentHealth -= takeDamage;
}
}
Well…this is a bad design…Update constantly grabbing a value just so it can be used later when TakeDamage is called…
Just have TakeDamage take the amount of damage being dealt and use that as a parameter. So when you call it, you also deal the amount of damage.
You need to look into GetComponent and that concept of instancing. It is simple to do. Get away from this static damage variable which seems to have just be a solution created because of a lack of knowledge of the proper way to connect scripts.
Thanks for the reply Brathnann, much appreciated. So i made some changes. The variable “damage” is working as expected inside the Player’s script component CombatScript. In the Enemy script, it gives me no errors in the code, but it still does not affect the variable “currentHealth”, which remains at the same value as in the Start method. I am still new in programming so i still try to correct any bad designs that occur.
public class Enemy : MonoBehaviour
{
public int maxHealth = 100;
public int currentHealth;
private CombatScript combatScript;
void Start()
{
currentHealth = maxHealth;
combatScript = GameObject.FindWithTag(“Player”).GetComponent();
}
public void TakeDamage()
{
currentHealth -= combatScript.damage;
}
}
You should probably show your other script as well, also, use code tags when posting on the forums, it helps with formatting your code on the forums.
That being said, How do you call TakeDamage? Do you have multiple enemies on the scene at once?
Also, while I applaud your attempt to fix things, this is actually what I meant. You can pass in the damage to the enemy script when you call the method. This is useful because you may at some point have additional sources of damage and you want it all to work.
I would also suggest you add some Debug.Log statements to print out the value of damage and currentHealth (after damage is taken)
public void TakeDamage(int damage)
{
currentHealth -= damage;
}