前断时间在做一个游戏项目,为了实现暂停还有游戏逻辑中用yield,自己写了一个类。代码如下:
using UnityEngine;
using System.Collections;
// if want gameobject pause Updata function, Please extend this class
public abstract class MyMonoBehaviour : MonoBehaviour {
//public abstract IEnumerator MyUpdate();
//public abstract IEnumerator MyStart();
protected bool pause = false;
private bool first;
public abstract void SystemUpdate();
public void Pause(){
pause = true;
}
public void Resume(){
pause = false;
}
bool isStart;
void Start () {
first = true;
isStart = true;
}
bool isRuning;
void OnDisable(){
isRuning = false;
}
// Update is called once per frame
void Update () {
if(first){
first = false;
return;
}
if(isStart){
if(pause == false){
StartCoroutine("MyStart");
//print("myStart");
isStart = false;
}
}
if(pause == false){
//StartCoroutine("SystemUpdate");
SystemUpdate();
}
if(isRuning == false){
StartCoroutine(_MyUpdate());
isRuning = true;
}
}
IEnumerator _MyUpdate(){
//print("pause"+pause);
while(true){
if(pause == false){
yield return StartCoroutine("MyUpdate");
}
else{
yield return null;
}
}
}
}
使用方法:需要用到暂停的组件,原来继承于MonoBehaviour 改为继承这个类。
原来的Update 改成MyUpdate。如果还需要用原来的的Update就该成 SystemUpdate。
研究的不够彻底,有兴趣的朋友可以一起讨论