[請益]unity在遊戲中設置紅綠燈發生錯誤

看板GameDesign (遊戲設計)作者 (rede1420)時間7年前 (2017/11/29 21:55), 編輯推噓5(5010)
留言15則, 5人參與, 7年前最新討論串1/2 (看更多)
如題 我嘗試在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

11/29 22:46, 7年前 , 1F
void Start()不能回傳值,要額外開coroutine
11/29 22:46, 1F

11/29 22:46, 7年前 , 2F

11/29 22:46, 7年前 , 3F
onds.html
11/29 22:46, 3F

11/30 01:02, 7年前 , 4F
程式碼的部分解決了,但是沒辦法帶入light資料,如圖二
11/30 01:02, 4F

11/30 01:03, 7年前 , 5F
是因為程式碼的關係嗎,還是物件的關係?
11/30 01:03, 5F

11/30 01:15, 7年前 , 6F
前面加個public像是public Light Red
11/30 01:15, 6F

11/30 01:17, 7年前 , 7F
這裡可以參考https://goo.gl/MSH2PE
11/30 01:17, 7F

11/30 02:10, 7年前 , 8F
解決問題了,謝謝你們
11/30 02:10, 8F

11/30 08:10, 7年前 , 9F
物件導向的觀念還不夠清楚 多多練習吧
11/30 08:10, 9F

11/30 08:11, 7年前 , 10F
另外變數範圍 全域或區域的分配也很重要
11/30 08:11, 10F

11/30 08:11, 7年前 , 11F
因為遊戲架構通常都不簡單 要好好的規劃變數規則
11/30 08:11, 11F

11/30 11:51, 7年前 , 12F
while(true)非必要還是不要在monoBehavior裡用
11/30 11:51, 12F

11/30 11:51, 7年前 , 13F
你需要的是coroutine或者Update()
11/30 11:51, 13F

11/30 22:54, 7年前 , 14F
謝謝大家的建議與指教,這次因為完工日期有點緊迫
11/30 22:54, 14F

11/30 22:55, 7年前 , 15F
迫不得以之下只能上來詢問大家,往後會再多多練習的
11/30 22:55, 15F
文章代碼(AID): #1Q7hnO6s (GameDesign)
文章代碼(AID): #1Q7hnO6s (GameDesign)