- Home /
Question by
ThierryH · Jun 29, 2014 at 07:52 PM ·
javascript
(c#)enemyHealth + playerAttack
Hello. I don`t understand what is wrong in this script, need a help.
I have 2 scripts: PlayerAttack & EnemyHealth. When I playing the scene, healthBar is immediately goes to zero, but I want that it decrease by 10.
public class EnemyHealth : MonoBehaviour { public int currentHealth = 100; public int maxHealth = 100;
public float healthBarLength;
// Use this for initialization
void Start ()
{
AdjustHealth(currentHealth);
healthBarLength = Screen.width / 2;
currentHealth = maxHealth;
}
// Update is called once per frame
void Update ()
{
// AdjustHealth(currentHealth);
AdjustHealth(0);
if(currentHealth == 0)
{
Death();
}
}
void OnGUI()
{
GUI.Box(new Rect(10, 10, healthBarLength, 20), currentHealth + "/" + maxHealth);
}
public void AdjustHealth(int adj)
{
currentHealth += adj;
if(currentHealth < 0)
{
currentHealth = 0;
}
if(currentHealth > maxHealth)
{
currentHealth = maxHealth;
}
if(maxHealth < 1)
{
maxHealth = 1;
}
healthBarLength = (Screen.width / 2) * (currentHealth / maxHealth); //возможно сделать перевести maxHealth во float
}
void Death()
{
Debug.Log("Enemy Die!!!");
}
}
public class PlayerAttack : MonoBehaviour { public GameObject target;
// Use this for initialization
void Start ()
{
EnemyHealth enemyHealth = target.GetComponent<EnemyHealth>();
}
// Update is called once per frame
void Update ()
{
if(Input.GetMouseButtonUp(0))
{
Attack();
}
}
void Attack()
{
float distance = Vector3.Distance(target.transform.position, transform.position);
Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
Debug.Log(direction);
// Debug.Log(distance);
if(distance <= 2.5 && direction > 0.3)
{
EnemyHealth enemyHealth = target.GetComponent<EnemyHealth>();
enemyHealth.AdjustHealth(-10);
}
}
}
Comment
Answer by jmgek · Jun 29, 2014 at 11:18 PM
enemyHealth.adjustHealth = enemyHealth.adjustHealth -= 10;
I think you are setting the enemy health to -10 when you are passing it through your adjustHealth.