This Unity Tutorial will show you 3 different methods to make a timer and be able to delay or wait between functions in your Unity3D scripts
Time Breakdown
- 0:30 - Setting up our variable
- 1:50 - Invoke method
- 4:40 - IEnumerator method
- 8:20 - Update method with Time.deltaTime
- 11:40 - Outro, thanks for watching :D
Check out the videos above to hear the explanation and see the code in action
/*/
* Script by Devin Curry
* www.Devination.com
* www.youtube.com/user/curryboy001
* Please like and subscribe if you found my tutorials helpful :D
* Twitter: https://twitter.com/Devination3D
/*/
using UnityEngine;
using System.Collections;
public class WaitExamples : MonoBehaviour
{
private float timer = 1f;
public int secs2Wait = 3;
public int[] totalSec = new int[3];
void Start ()
{
InvokeRepeating("TimerInvoke", 1, 1);
StartCoroutine(TimerEnumerator());
}
void TimerInvoke()
{
if(totalSec[0] < secs2Wait)
totalSec[0]++;
else
CancelInvoke("TimerInvoke");
}
IEnumerator TimerEnumerator()
{
for(int ii =0; ii < secs2Wait; ii++)
{
yield return new WaitForSeconds(1);
totalSec[1]++;
}
}
void Update ()
{
TimerUpdate();
}
void TimerUpdate()
{
if(totalSec[2] < secs2Wait)
{
if(timer > 0)
timer -= Time.deltaTime;
else if (timer <= 0)
{
totalSec[2]++;
timer = 1f;
}
}
}
}