1. Time.time
using UnityEngine;
public class TimeTest : MonoBehaviour
{
public float secound = 10;
void Update()
{
Timing();
}
private float nextTime = 1;
private void Timing()
{
if (secound <= 0) return;
if(Time.time >= nextTime)
{
secound -= 1;
Debug.Log(secound);
nextTime = Time.time + 1;
}
}
}
2. Time.deltaTime
using UnityEngine;
public class TimeTest : MonoBehaviour
{
public float secound = 10;
void Update()
{
Timing();
}
private float waitTime;
private void Timing()
{
if (secound <= 0) return;
waitTime += Time.deltaTime;
if(waitTime >=1)
{
secound--;
Debug.Log(secound);
waitTime = 0;
}
}
}
3. InvokeRepeating
using UnityEngine;
public class TimeTest : MonoBehaviour
{
public float secound = 10;
void Start() => InvokeRepeating("Timing", 1, 1);
private void Timing()
{
if (secound <= 0) return;
secound--;
Debug.Log(secound);
}
}
4. 协程
using System.Collections;
using UnityEngine;
public class TimeTest : MonoBehaviour
{
public float secound = 10;
IEnumerator Start() //将Start方法作为协同程序,则不必调用StartCoroutine
{
while (secound > 0)
{
yield return new WaitForSeconds(1);
secound--;
Debug.Log(secound);
}
}
}
5. 线程
using System.Threading;
using UnityEngine;
public class TimeTest : MonoBehaviour
{
public float secound = 10;
void Start()
{
Thread thread = new Thread(Timing);
thread.Start();
}
private void Timing()
{
while (secound > 0)
{
Thread.Sleep(1000);
secound--;
Debug.Log(secound);
}
}
}