- Home /
Want health to decrement longer stays on trigger
When OnTriggerEnter event is fired then health decrements by 5. Now I want it to check every so many seconds and if still there then decrement another 5.
I had absolutely no success with OnTriggerStay so OnTriggerEnter sets a bool to true and OnTriggerExit sets to false.
What I want is while true it will decrement but obviously not on Update.
I have tried calling a coroutine with a yield in which waits the first time, and then decrements on every update so I am obviously not calling it correctly
The Coroutine is simply this
IEnumerator OnSpikes()
{
audio.PlayOneShot(spikesSound);
yield return new WaitForSeconds(5.0f);
health -=1;
}
I have tried calling the coroutine from all over the place (can't even remember them all) and in while loops Anyway, can someone lead me in the right direction (I have searched and searched and tried all sorts of things but I'm obviously missing something)
thanks in advance }
Answer by shaderop · Sep 29, 2012 at 07:28 AM
Try something like this:
private bool isInTrigger = false;
void Start()
{
StartCoroutine(OnSpikes());
}
void OnTriggerEnter(Collider other)
{
isInTrigger = true;
}
void OnTriggerExit(Collider other)
{
isInTrigger = false;
}
IEnumerator OnSpikes()
{
while (true)
{
if (isInTrigger)
{
audio.PlayOneShot(spikesSound);
health -=1;
}
yield return new WaitForSeconds(5.0f);
}
}
This answer should work too -- the one downside is, since it's running all the time, you'll get different waits for the first run-through after each trigger. e.g. if you're 2 seconds through "WaitForSeconds" when the bool is turned on, your code will wait 3 seconds to decrement the health.
I see what you mean kmeboe. For this instance it will be okay, but will definitely look into your solution. For now will stick with this as the assignment is due $$anonymous$$onday and it is extra functionality that I have added in, Thanks again to you both
@Overflo You're very welcome. But as kmeboe said, the coroutine will be running all the time, but I don't think that should cause any noticeable performance issues since it's only invoked every few seconds and the code is very $$anonymous$$imal.
Answer by kmeboe · Sep 29, 2012 at 07:24 AM
Greetings,
If you call StartCoroutine before the previous one has ended, this error will occur. My advice is to set a boolean to "true" in OnTriggerEnter (or wherever), then during Update() launch your Coroutine if the boolean is "true". The end of the Coroutine will then set this boolean to "false".
See the answer here for an example: http://answers.unity3d.com/questions/240794/coroutine-for-reloading.html
-Kevin
Your answer
Follow this Question
Related Questions
Work around for onTriggerStay? 1 Answer
Multiple Cars not working 1 Answer
How to run a coroutine if in a trigger but run a different one if outside it? 1 Answer
Call function on all objects in trigger 2 Answers
Distribute terrain in zones 3 Answers