GrKl
1
Hello all,
I am trying to make a script to be able to attack and kill my enemies.
All works fine, untill I make a prefab of my enemy (with his scripts attached) and create 2 enemies with this prefab in the script.
Whatever I do, only one enemy gets damage, and only when he is dead can I hurt the second one.
Plus when the second one is dead, I do not receive expected XP.
Here is the players attack code:
public class Warrior : MonoBehaviour {
private float playerDamage;
public float strength;
public int distance = 5;
void Start () {
PlayerHealth playerHealth = gameObject.GetComponent<PlayerHealth>();
PlayerMana playerMana = gameObject.GetComponent<PlayerMana>();
playerHealth.endurance = 20;
playerHealth.armor = 100;
playerHealth.magicResist = 50;
playerMana.intelligence = 10;
strength = 10.0f;
playerDamage = 1.1f * strength;
}
void Update () {
if(Input.GetKeyDown(KeyCode.F))
{
GameObject[] enemies;
enemies = GameObject.FindGameObjectsWithTag("enemy");
foreach (GameObject enemy in enemies)
{
if(enemy != null && Vector3.Distance(transform.position, enemy.transform.position) < distance)
{
playerAttackHit();
print (enemies);
}
}
}
}
public void playerAttackHit()
{
EnemyHealth enemyHealth = GameObject.FindGameObjectWithTag("enemy").GetComponent<EnemyHealth>();
enemyHealth.enemyCurHealth -= playerDamage;
}
}
and here is the “enemyHealth” code:
public class EnemyHealth : MonoBehaviour {
public float enemyCurHealth;
private int enemyMaxHealth;
// Use this for initialization
void Start () {
enemyCurHealth = 99999;
enemyMaxHealth = 50;
}
// Update is called once per frame
void Update () {
PlayerLevel playerLevel = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerLevel>();
if(enemyCurHealth > enemyMaxHealth)
{
enemyCurHealth = enemyMaxHealth;
}
if(enemyCurHealth < 1)
{
playerLevel.curExp = 1;
Destroy (gameObject);
}
}
}
thank you for any help possible
I would suggest that you add a parameter, like GameObject enemy, for the PlayerAttackHit. Then in the method just call enemy take damage whatever, and in your foreach loop for the enemy in enemies, just call PlayerAttackHit(enemy);