DanProd
February 19, 2019, 1:38pm
1
Title says it all, basically I have a problem where my script damage the player in every second, I want to tell the script that it should be waiting like 5 seconds before damaging again.`{
public int Pain = 1;
void Start()
{
}
void OnTriggerStay (Collider other)
{
{
if (other.gameObject.tag == "Player")
{
StartCoroutine(CountDown());
Vector3 damageDirection = other.transform.position - transform.position;
damageDirection = damageDirection.normalized;
FindObjectOfType<PlayerHealth>().DamagePlayer(Pain, damageDirection);
}
}
}
IEnumerator CountDown()
{
print(Time.time);
yield return new WaitForSeconds(1000);
print(Time.time);
}
}
`
TreyH
February 19, 2019, 1:51pm
2
I don’t think you need a Coroutine at all:
private float hitLast = 0;
private float hitDelay = 5;
void OnTriggerStay (Collider other)
{
if (other.gameObject.tag == "Player")
{
if (Time.time - hitLast < hitDelay)
return;
Vector3 damageDirection = other.transform.position - transform.position;
damageDirection = damageDirection.normalized;
FindObjectOfType<PlayerHealth> ().DamagePlayer (Pain, damageDirection);
hitLast = Time.time;
}
}
visca_c
February 19, 2019, 3:01pm
3
put the damage function in coroutine too, or else they would execute together without delay. Something like this:
(Edit: if you want to use OnTriggerStay, you probably want to make sure you are not starting co-routine every frame when player is in trigger.)
bool coroutineRunning;
IEnumerator DmgAfterTime(float seconds)
{
coroutineRunning=true;
yield return new WaitForSeconds(seconds);
playerHealth.DamagePlayer (Pain, damageDirection);
coroutineRunning=false;
}
void OnTriggerStay(Collider other)
{
//if not running
if(!coroutineRunning)
StartCoroutine(DmgAfterTime(5));
}
Another way to run function after time is to use delegate in a cotoutine.
public delegate void RunFuncDelegate();
public IEnumerator RunFuncAfterTime(RunFuncDelegate Func, float time)
{
yield return new WaitForSecondsRealtime(time);
Func();
}
This way you can call any function after a delay.
StartCoroutine(RunFuncAfterTime(() => playerHealth.DamagePlayer (Pain, damageDirection), 5));