作者sammon (海带)
看板GameDesign
标题Re: [请益]unity在游戏中设置红绿灯发生错误
时间Thu Nov 30 00:27:54 2017
※ 引述《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
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 118.165.6.223
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/GameDesign/M.1511972879.A.739.html
1F:→ rede1420: 谢谢你详细的说明,问题解决了 11/30 02:11