作者rede1420 (rede1420)
看板GameDesign
標題[請益]unity在遊戲中設置紅綠燈發生錯誤
時間Wed Nov 29 21:55:34 2017
如題
我嘗試在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
想問問大家要怎麼修正才可以正常執行
謝謝大家
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.134.69.177
※ 文章網址: https://www.ptt.cc/bbs/GameDesign/M.1511963736.A.1B6.html
推 cjcat2266: void Start()不能回傳值,要額外開coroutine 11/29 22:46
→ cjcat2266: onds.html 11/29 22:46
→ rede1420: 程式碼的部分解決了,但是沒辦法帶入light資料,如圖二 11/30 01:02
→ rede1420: 是因為程式碼的關係嗎,還是物件的關係? 11/30 01:03
推 sammon: 前面加個public像是public Light Red 11/30 01:15
→ rede1420: 解決問題了,謝謝你們 11/30 02:10
推 cowbaying: 物件導向的觀念還不夠清楚 多多練習吧 11/30 08:10
推 cowbaying: 另外變數範圍 全域或區域的分配也很重要 11/30 08:11
→ cowbaying: 因為遊戲架構通常都不簡單 要好好的規劃變數規則 11/30 08:11
推 chargo: while(true)非必要還是不要在monoBehavior裡用 11/30 11:51
→ chargo: 你需要的是coroutine或者Update() 11/30 11:51
→ rede1420: 謝謝大家的建議與指教,這次因為完工日期有點緊迫 11/30 22:54
→ rede1420: 迫不得以之下只能上來詢問大家,往後會再多多練習的 11/30 22:55