- Home /
Damage not reducing to enemy every second
hi there, I have an issue with my damage system for enemy. i want it so the enemies health decreases as the weapon is touching it. So far what happens is that it will do damage once on impact but no more. the only way to do more damage is to move sword away and re-hit the enemy. I want it so that when the sword is on the enemy, it does damage continously, not once.
Heres the script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class sworddamage : MonoBehaviour {
public double damage;
public double delaytime = 1.4;
public GameObject Enemy;
public Animator animator;
public bool damageable;
void Update()
{
//StartCoroutine(takeDamage());
if (Input.GetButtonDown("Fire1"))
{
animator.SetBool("attack", true);
}
if (Input.GetButtonUp("Fire1"))
{
animator.SetBool("attack", false);
}
}
void OnCollisionEnter2D (Collision2D Col)
{
if(Col.gameObject.tag == "Enemy"){
Enemy enemy = Col.transform.gameObject.GetComponentInParent(typeof(Enemy)) as Enemy;
if (enemy != null)
{
//if (damageable = true)
//{
enemy.TakeDamage((int)damage);
//damageable = false;
// }
if(enemy.Died == true)
{
}
}
}
}
IEnumerator takeDamage()
{
if (damageable == false)
{
yield return new WaitForSeconds((int)delaytime);
damageable = true;
}
}
}
Thanks in advance!
Answer by GDGames0302 · Jan 30, 2021 at 07:25 AM
Hi. You should use OnCollisionStay2D. This way, you deal damage to the enemy every frame. If that is too much, you could increase the enemy's health, or you could decrease the dame dealt per frame. Or you can do something like this: for example, you execute the OnCollisionStay2D only if a bool is false. Initially, you set that bool to false, and in the OnCollisionStay2D you can set that bool to true and start a coroutine with WaitForSeconds that sets that bool back to false. This way the OnCollisionStay2D executes at the given time by the WaitForSeconds.
Answer by Natrx · Feb 20, 2021 at 05:15 AM
Thanks! Sorry for the late response but i will give it a go
Your answer
Follow this Question
Related Questions
Please, I need a damage script 2 Answers
Make screen flash red on Damage 2 Answers
Quick question about DamageReceiver script from FPS tutorial 1 Answer
Colliding damage on Enemy even when not attacking? 1 Answer
Health Question 1 Answer