为什么要是用携程?
我需要计算1—10000的累加,我们应该怎么做?
1、首先我们写一个累加方法:
public void GetAccumulationResult()
{
int accumulationResult=0;
for(int i=1;i<=10000;i++)
{
accumulationResult+=i;
}
print("1-1000的累加结果为:"+accumulationResult);
}
2、这个方法应该在哪里调用呢?
不论你是在Update(),Start()......任何一个方法里调用,都会造成系统的停顿。我们知道C#中有多线程、异步可以实现,那么在unity中如果实现让游戏正常运行不卡顿,又能正确获得想要的结果呢?
答案就是:Coroutine(协同程序 简称 协程 )
3、协程的使用
首先对累加的方法进行改造
IEnumerator GetAccumulationResult()
{
int accumulationResult=0;
for(int i=1;i<=1000;i++)
{
accumulationResult+=i;
yield return null; //下一帧再执行后续代码
}
print("1-1000的累加结果为:"+accumulationResult);
}
在Update方法中调用
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))//按下空格执行
{
print("游戏正常运行-1");
StartCoroutine("GetAccumulationResult"); //协程开始
print("游戏正常运行-2");
}
}
游戏运行后按3次空格
控制台德输出结果是这样的:
游戏正常运行-1
游戏正常运行-2
游戏正常运行-1
游戏正常运行-2
游戏正常运行-1
游戏正常运行-2
1-1000的累加结果为:500500
1-1000的累加结果为:500500
1-1000的累加结果为:500500