Hello guys
I want to make a game with a stationary player and enemies moving towards the player. When the enemy hits the player they will attack each other. It works with one enemy but when I duplicate the enemy the player only attacks the first one and the second one never takes damage…
This is my EnemyHealth script:
public class EnemyHealth : MonoBehaviour
{
public float health;
public float maxHealth = 10f;
public Image healthBar;
// Start is called before the first frame update
void Start()
{
health = maxHealth;
}
public void TakeDamage(float damage)
{
health -= damage;
healthBar.fillAmount = health / maxHealth;
if(health <= 0)
{
Destroy(gameObject);
}
}
}
And here is the PlayerDamage script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerDamage : MonoBehaviour
{
public EnemyHealth enemyHealth;
public float damage = 3f;
public float atkSpeed = 1.0f;
private float elapsedTime;
private bool canAttack;
void OnTriggerEnter2D(Collider2D trig)
{
if(trig.gameObject.CompareTag("Enemy"))
{
canAttack = true;
}
else
{
canAttack = false;
}
}
void Update()
{
if(canAttack && enemyHealth != null)
{
elapsedTime += Time.deltaTime;
if(elapsedTime > atkSpeed)
{
enemyHealth.TakeDamage(damage);
elapsedTime -= atkSpeed;
}
}
}
}
I’ve done some research on the topic and found out that I need to interact with the separate enemy’s health instead of a single. Currently the script focuses on the “overall” EnemyHealth() but I want it to interact with the specific enemy’s EnemyHealth()
I just can’t figure out how to implement it in my project…
Here is the discussion I found I can't kill more copies of the same enemy?
Hope someone can help!