- Home /
Question by
JoranvanDolder · Aug 25, 2017 at 11:26 PM ·
coroutineattackontriggerstayvoidattacking
How can I make an event happen every 2 seconds in the OnTriggerStay void?
How can I make an ebent happen every 2 seconds in the OnTriggerStay void? I want to run a Enemy Attack event where I take the player's health and -= by the Enemy damage.
Comment
Answer by $$anonymous$$ · Aug 26, 2017 at 12:09 AM
You could use OnTriggerStay() as co-routine:
void OnTriggerStay()
{
//damage code
yield WaitForSeconds(2);
}
You could set and un-set a bool with OnTriggerEnter() and OnTriggerExit() and have the damage calculated in your update function:
public class your_script : MonoBehaviour {
private float lastTime;
[SerializeField]
private float delay = 2f;
private bool inDamageZone;
void OnEnable()
{
inDamageZone = false;
lastTime = Time.timeSinceLevelLoad;
}
private void OnTriggerEnter(Collider other)
{
inDamageZone = true;
lastTime = Time.deltaTime;
}
private void OnTriggerExit(Collider other)
{
inDamageZone = false;
}
void Update () {
if (inDamageZone && Time.timeSinceLevelLoad > lastTime + delay)
{
//player damage code
}
}
}
Answer by zachwuzhere · Aug 26, 2017 at 12:10 AM
Hope this helps...
float SavedTime = 0;
float DelayTime = 2;
void OnTriggerStay(){
if( (Time.time - SavedTime) > DelayTime ) {
SavedTime=Time.time;
//Anything in here will be called every two seconds
print(DelayTime +" seconds have passed");
}
}
Your answer
Follow this Question
Related Questions
How do I fix an issue with my enemy instantly dying? 1 Answer
Enemy attack constantly with a coroutine 1 Answer
Timed Attack System 1 Answer
Applying Damage 5 Answers
Need Help with a Null Reference 1 Answer