Re: [请益]unity在游戏中设置红绿灯发生错误

楼主: sammon (海帶)   2017-11-30 00:27:54
※ 引述《rede1420 (rede1420)》之铭言:
: 如题
: 我尝试在unity里面设置红绿灯
: 以下是JS的写法,确认可以执行,但我想将它改成C#写法就发生错误了
: var Red : Light;
: var Green : Light;
: var Yellow : Light;
: function Start()
: {
: Yellow.enabled = false;
: while(true)
: {
: Green.enabled = true;
: Red.enabled = false;
: yield WaitForSeconds(10);
: Yellow.enabled = true;
: Green.enabled = false;
: yield WaitForSeconds(4);
: Red.enabled = true;
: Yellow.enabled = false;
: yield WaitForSeconds (10);
: }
: }
: 正常执行如下
: https://imgur.com/a/8BJyo
: 以下是修改过的C#写法
: using System.Collections;
: using System.Collections.Generic;
: using UnityEngine;
: public class Tflc : MonoBehaviour
: {
: Light Red;
: Light Green;
: Light Yellow;
: // Use this for initialization
: void Start()
: {
: Yellow.enabled = false;
: while (true)
: {
: Green.enabled = true;
: Red.enabled = false;
: yield return new WaitForSeconds(10);
: Yellow.enabled = true;
: Green.enabled = false;
: yield return new WaitForSeconds(4);
: Red.enabled = true;
: Yellow.enabled = false;
: yield return new WaitForSeconds(10);
: }
: }
: }
: 在void Start()显示说void不是Iterator接口
: 将它改成IEnumerator Start()后
: 会没有办法套用设置的light物件
: 如下图
: https://imgur.com/a/BL7rq
: 想问问大家要怎么修正才可以正常执行
: 谢谢大家
你宣告好IEnumerator之后,要呼叫一个MonoBehavior底下的method去执行他
因为你这个Start是继承自MonoBehaviour
所以在游戏开始后会先执行 Start() 一次
console才会跳出错误
建议把
IEnumerator Start(){
//红绿灯的算法
}
改成
IEnumerator something(){
//红绿灯的算法
}
然后在Start里面呼叫StartCoroutine去执行
像这样
void Start(){
StartCoroutine("something");
}
可以参考官方的文件
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
作者: rede1420 (星晴)   2017-11-30 02:11:00
谢谢你详细的说明,问题解决了

Links booklink

Contact Us: admin [ a t ] ucptt.com