Unity三种方法实现延迟执行

1.计时器

1.定义一个float 的变量
2.然后逐帧减去Time.DeltaTime 的值,直到最后小于0
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

class Test : MonoBehaviour{
    
    
	private float timer = 2f;
	
	void Update(){
    
    
		if(timer < 0){
    
    
			//Doing Something...
		}else{
    
    
			timer -= Time.DeltaTime;
		}
	}
}

1.协程

1.定义一个返回值为 IEnumerator 的方法,在通过StartCoroutine开启这个协程即可。

注意这里需要使用的是IEnumerato而不是IEnumerable这两者的区别:

  • IEnumerator:是一个迭代器接口
  • IEnumerable:是在IEnumerator基础上的一个封装接口,有一个GetEnumerator()方法返回IEnumerator

StartCoroutine 的几种重载方法

  • StartCoroutine(string methodName): 这种只适用于没有参数的情况
  • StartCoroutine(IEnumerator routine):通过方法的形式调用
  • StartCoroutine(string methodName, object values) :适用于有参数的使用,并在后面依此传入参数的值


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

class Test : MonoBehaviour{
    
    
	void Start(){
    
    
		StartCoroutine(Func(2.0f));
		//StartCoroutine("Func", 2.0f)
	}

	IEnumerator Func(float delay){
    
    
		yield return new WaitForSeconds(delay); //程序在这里等待delay长的时间后,再去往下执行
		//Doing Something...
	}
}

yield的补充

  • yield return null:暂停协程等待下一帧继续执行

  • yield return 0或其他数字:暂停协程等待下一帧继续执行

  • yield return new WairForSeconds(时间):等待规定时间后继续执行

  • yield return StartCoroutine("协程方法名"):开启一个协程(嵌套协程)


  • yield return GameObject; 当游戏对象被获取到之后执行
  • yield return new WaitForFixedUpdate():等到下一个固定帧数更新
  • yield return new WaitForEndOfFrame():等到所有相机画面被渲染完毕后更新
  • yield break; 跳出协程对应方法,其后面的代码不会被执行

3.Invoke调用

Invoke也是Unity中一种延迟调用机制,但是被调用的函数不能有参数

Invoke的常用两种方法

  • Invoke(string methodName, float time) : 延迟time秒之后调用methodName函数
  • InvokeRepeating(string methodName, float time, int repeatRate):重复repeatRate次调用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

class Test : MonoBehaviour{
    
    
	void Start(){
    
    
		Invoke("Func", 2);
		//InVoke("Func", 2 ,3);
	}

	void Func(float delay){
    
    
		Debug.Log("Doing Something... ")
		//Doing Something...
	}
}

猜你喜欢

转载自blog.csdn.net/blastospore/article/details/130046019