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