Hi, still new to development. The problem: when my player collides with one of multiple enemies every enemy starts the attack animation. How to I get only one of the enemies to execute the attack animation??
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Zombie : EnemyBehaviour
{
protected override void takeDamage(int damage)
{
//play hurt sound
//play animation if available
//if the sound is playing don't play again till over otherwise play sound
if(!sound[0].isPlaying)
sound[0].Play();
//call base.takeDamage to decrement health
base.takeDamage(damage);
}
void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log(collision.gameObject.GetComponent<Collider2D>());
if (collision.gameObject.tag.Equals("Player"))
{
isAttacking = true;
isMoving = false;
Debug.Log(animate.GetBool("isAttacking"));
Debug.Log(animate.GetBool("isMoving"));
}
}
void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag.Equals("Player"))
{
isAttacking = false;
isMoving = true;
}
}
private void attackPlayer()
{
animate.SetBool("isAttacking", true);
animate.SetBool("isMoving", false);
}
private void Update()
{
if (isAttacking)
{
attackPlayer();
}
else
{
animate.SetBool("isAttacking", false);
animate.SetBool("isMoving", true);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Animations;
using UnityEngine;
//class contains all the needed data and components of Enemy objects
public class EnemyBehaviour : MonoBehaviour
{
[System.Serializable]
public class EnemyStats
{
public int health = 10;
public float speed = 1.0f;
public int atk_damage = 1;
}
public EnemyStats stats = new EnemyStats();
//animator component to control animations
// [HideInInspector]
public Animator animate;
//Rigidbody component to control movement
[HideInInspector]
public Rigidbody2D rb;
//audio source array to store enemy sounds
public AudioSource[] sound;
//bool for if enemy is attacking somethinh
public static bool isAttacking;
//bool for is the enemy is moving or not
public static bool isMoving;
private void Awake()
{
animate = this.gameObject.GetComponent<Animator>();
//_collider = GetComponent<Collider2D>();
sound = this.gameObject.GetComponents<AudioSource>();
rb = this.gameObject.GetComponent<Rigidbody2D>();
}
//method to decrement the amount of health
//destroys enemy when health is zero
protected virtual void takeDamage(int damage)
{
//decrement our max health by damage amount
stats.health -= damage;
if(stats.health <= 0)
{
//play death animation and sound
animate.Play("Death");
//call killenemy to destroy this
GameManager.KillEnemy(this);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.name.Equals("Hero"))
{
Physics2D.IgnoreLayerCollision(9, 14, true);
}
}
}