协程简而言之就是无条件的跳出当前执行并挂起,直到外部调用下一次继续执行才开始,可以理解为挂起程序
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour
{
private string dialogStr = "协程打印字体测试";
private string showMsg;
private float speed = 5.0f;
//注意要用IEnumerator作为返回属性
IEnumerator ShowDialog()
{
float timeSum = 0.5f;
while (showMsg.Length < dialogStr.Length)
{
timeSum += speed * Time.deltaTime;
showMsg = dialogStr.Substring(0, System.Convert.ToInt32(timeSum));
Debug.Log(showMsg);
yield return null;//协程中断返回位置
}
}
void Start()
{
showMsg = "";//初始化字符串变量
StartCoroutine(ShowDialog());//要在这里添加协程函数名否则不能执行
}
void Update()
{
ShowDialog();
}
}

1786

被折叠的 条评论
为什么被折叠?



