Is there something like the update function but where I can set it to wait for a certain amount of time before it repeats?
Take a look at coroutines
You can just have it repeat loop over and over, and have it delay at the beginning/end/wherever you want.
Sorry I’m really bad at understanding the references. What if for example I had a Int at 100 and I wanted it to decrease by 1 every 2 seconds. Could you possibly give me an example?
Well with this example, InvokeRepeating would be a simpler way to understand/use…
public class Example: MonoBehaviour
{
int health = 100;
void Start()
{
InvokeRepeat("LowerHealth",1.0f, 2.0f); //in one second, start calling this function, every 2secs
}
void LowerHealth()
{
health--; // lower health value by 1
}
}
Here’s the way with Coroutines, just so you can see how those work/differ:
public class Example: MonoBehaviour
{
int health = 100;
void Start()
{
StartCoroutine("LowerHealth");
// or do it this way if you want to have the "handle" to the coroutine so you can stop it easier later..
//IEnumerator myCoroutine = StartCoroutine("LowerHealth");
}
IEnumerator LowerHealth()
{
while (true) // this just equates to "repeat forever"
{
yield return new WaitForSeconds(2f); // "pauses" for 2 seconds.. note, the actual game doesn't pause..
health--; // lower health value by 1
}
}
}
The StartCoroutine command would kick off this LowerHealth method. Within it, it would continually loop forever. At the start of the loop, it would wait for 2 seconds to pass, then lower the health by 1.
There are smarter ways to handle the wait so that it doesn’t keep reallocating memory, but we’ll leave that alone for now while you figure this out. There’s some good info on coroutines here:
Both of the methods you gave me go down way faster then 1 every 2 seconds. Like, both would be down to zero after 3 seconds. Something to note, the Coroutine one waited 2 seconds before going down really fast while the Invoke one just started going down immediately. It would seem the Coroutine one waits the two seconds but doesn’t loop back while the Invoke one doesn’t wait or loop. Solution?
Oh crap, sorry, for both examples… change Update to Start. ![]()
I’ve modified the code above. That would have had them basically spawning several iterations of the same function each frame, rather than just have one iteration of the function doing its thing.
Yup all’s good now! Thanks for the help!
No problem