Hello, I am a little new to unity (started about 3 months ago), and I am currently having an issue with my attack script.
I used the following video to make my character's attack system:
https://www.youtube.com/watch?v=1QfxdUpVh5I&t=388s&list=WL&index=3
However, when attacking one enemy all of my enemies with the "TakeDamage" function will take damage.
How would I fix this and only deal damage to only the enemies within the attack Range?
Scripts:
attack script
private float timeBtwAttack;
public float startTimeBtwAttack;
public Transform attackPos;
public float attackRange;
public LayerMask WhatIsEnemies;
public int damage = 1;
void Update()
{
if (timeBtwAttack <= 0) {
if (Input.GetKey (KeyCode.R)) {
timeBtwAttack = startTimeBtwAttack;
Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll (attackPos.position, attackRange, WhatIsEnemies);
for (int i = 0; i < enemiesToDamage.Length; i++) {
enemiesToDamage [i].GetComponent ().TakeDamage (damage);
}
}
} else {
timeBtwAttack -= Time.deltaTime;
}
}
void OnDrawGizmosSelected(){
Gizmos.color = Color.red;
Gizmos.DrawWireSphere (attackPos.position, attackRange);
}
}
and The enemy script:
void Awake (){
Instance = this;
}
private void Flash(){
EnemyHealthect.Instance.StartCoroutine(ColorChange());
}
private IEnumerator ColorChange(){
var Renderer = SpriteRenderer;
if (GetComponent() != null) {
for (int i = 1; i <= timesToFlash; i++) {
GetComponent().material.color = FlashColor;
yield return new WaitForSeconds (FlashDelay);
GetComponent().material.color = NormalColor;
yield return new WaitForSeconds (FlashDelay);
}
}
}
void Update() {
if (health<=0){
health = 0;
Destroy (gameObject);
}
}
public void TakeDamage(int damage){
health -= damage;
EnemyHealthect.Instance.Flash ();
Debug.Log (health);
}
}
thanks
↧