Coroutines & Yield 协同程序 & 中断

untiy中常用的方法:

Coroutines & Yield 协同程序 & 中断

他的作用是这样的:

写游戏代码,往往最终需要代码为连续的事件.结果会像这样::

public class example : MonoBehaviour {
	private int state = 0;
	void Update() {
		if (state == 0) {
			state = 1;
			return;
		}
		if (state == 1) {
			state = 2;
			return;
		}
	}
}

往往使用中断语句更为方便.中断语句是一个特殊的返回类型,它确保函数从中断语句的下一行继续执行.

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
	IEnumerator Awake() {
		while (true) {
			yield return null;
			yield return null;
		}
	}
}

从官方解释可以看出,他是一种可以连续执行,且保证步骤执行的程序。

他是协同程序,并不是附加线程,在主线程中执行。

在实际使用中,类似斗地主这种需要玩家循环出牌的,可以这样用:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    void Start() {
        StartCoroutine(a1());
    }

    IEnumerator a1() {
        print("a1");
        yield return new WaitForSeconds(4);
        StartCoroutine(a2());
       
    }
    IEnumerator a2()
    {
        print("a2");
        yield return new WaitForSeconds(4);
        StartCoroutine(a3());
    }
    IEnumerator a3()
    {
        print("a3");
        yield return new WaitForSeconds(4);
        StartCoroutine(a1());
    }
}

从代码可以看出,yield return 和方法里面的return概念完全不一样,并不是返回什么东西,而是保证他之前的程序先执行,这样可以一个一个的执行,不会同时一起执行。

你可能感兴趣的:(Coroutines & Yield 协同程序 & 中断)