Question by
tios · Nov 29, 2021 at 05:31 PM ·
scripting beginnergetcomponentstart
Script doesn't take health player script
Hello, I am working on a shooter where player get damage if he doesn't hit an ennemy. I do a GetComponent of my player and do TakeDamage() but it say that my player has currentHealth=0.
Do you know how to fix it ?
Thanks you for your help.
Bullet.cs :
public class Bullet : MonoBehaviour
{
public GameObject player;
void OnCollisionEnter2D(Collision2D collision)
{
if (IsAnEnnemy(collision))
{
GameObject hit = collision.gameObject;
Debug.Log($"Ennemy spotted : { (hit != null?hit.name:" NoNe")}");
}
else
{
Debug.Log("Not an ennemy...");
PlayerHealth health = player.GetComponent<PlayerHealth>();
health.TakeDamage();
}
Destroy(gameObject);
}
bool IsAnEnnemy(Collision2D col)
{
return col.collider.tag == "Ennemy";
}
}
PlayerHealth.cs :
public class PlayerHealth : MonoBehaviour
{
public Image state;
public Sprite[] spriteHealth;
public Animator animator;
public int maxHealth = 3;
public int currentHealth;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
state.sprite = spriteHealth[currentHealth-1];
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
TakeDamage();
}
if(currentHealth == 0)
{
Debug.Log("You die");
Destroy(gameObject);
}
}
public void TakeDamage()
{
if(currentHealth != 0)
{
currentHealth--;
animator.SetInteger("health", currentHealth);
state.sprite = spriteHealth[currentHealth - 1];
}
Debug.Log(currentHealth);
}
}
Comment