I’ve created a script that should reduce the health of the “Enemy” by 10 when I press the key F, I’ll show you the code. The problem is, it’s subtracting this 10 three times, so it’s running the code two times more than it should. Any ideas?
PlayerAttack Script:
using UnityEngine;
using System.Collections;
public class PlayerAttack : MonoBehaviour {
public GameObject target;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyUp(KeyCode.F)) {
Attack();
}
}
private void Attack() {
EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
eh.AdjustCurrentHealth(-10);
}
}
EnemyHealth script, so you can see the AdjustCurrentHealth function:
using UnityEngine;
using System.Collections;
public class EnemyHealth : MonoBehaviour {
public int maxHealth = 100;
public int currentHealth = 100;
public float healthBarLength;
// Use this for initialization
void Start () {
healthBarLength = Screen.width / 2;
}
// Update is called once per frame
void Update () {
AdjustCurrentHealth (0);
}
void OnGUI() {
GUI.Box(new Rect(10, 50, healthBarLength, 20), currentHealth + "/" + maxHealth);
}
public void AdjustCurrentHealth(int adj) {
if((currentHealth += adj) < 1) {
currentHealth = 0;
} else if((currentHealth += adj) > maxHealth) {
currentHealth = maxHealth;
} else {
currentHealth += adj;
}
healthBarLength = (Screen.width / 2) * (currentHealth / (float) maxHealth);
}
}