2014-04-16 71 views
1

我在使用C#編寫的日/夜循環腳本擺弄。 我不知道它是否有什麼好處,我只是在C#中嘗試,因爲我是新手。 我想我在這裏有一個相當不錯的代碼,除非我測試遊戲,否則Debug不會說任何東西。當我測試它,它會說:無法從源類型轉換爲目標類型迭代轉換

InvalidCastException: Cannot cast from source type to destination type. cycleFlow.DayNightCycle() (at Assets/Scripts/cycleFlow.cs:28) cycleFlow.Update() (at Assets/Scripts/cycleFlow.cs:14)

這是我有:

using UnityEngine; 
using System.Collections; 

public class cycleFlow : MonoBehaviour { 

    private Color night; 
    private Color day; 

    void Start() { 

    night [0] = 30; 
    night [1] = 30; 
    night [2] = 30; 

    day [0] = 255; 
    day [1] = 255; 
    day [2] = 255; 

    } 

    void Update() { 
    DayNightCycle(); 
    } 

    void DayNightCycle() 
    { 

    foreach (SpriteRenderer child in transform) 
     if(Input.GetKeyDown(KeyCode.Q)) 
     child.color = Color.Lerp(child.color, night, Time.deltaTime); 

    foreach (SpriteRenderer child in transform) 
     if(Input.GetKeyDown(KeyCode.E)) 
     child.color = Color.Lerp(child.color, day, Time.deltaTime); 

    } 
} 

這是怎麼回事? (第一次BTW在這裏發帖,如果對不起,我做錯什麼)

回答

1

試試這個簡單的修改讓過去的錯誤:

foreach (SpriteRenderer child in transform.GetComponentsInChildren<SpriteRenderer>()) 

的進一步深入我會試着記住的幀率。如果您可以從Start函數中獲得緩存,您可能需要緩存這些渲染器。此外,我會將if(Input.GetKeyDown(KeyCode.E))移到您的循環之外而不是內部。

編輯:回到這個我也注意到你只是按下鍵而不是按鍵時按下。 (見GetKeyDown,GetKeyGetKeyUp之間的差異)。你可以試試這樣的:

using UnityEngine; 
using System.Collections; 
using System.Collections.Generic; 

public class cycleFlow : MonoBehaviour 
{ 

    private Color night; 
    private Color day; 
    private IEnumerable<SpriteRenderer> childSpriteRenderers; 

    void Start() 
    { 
    night = new Color(30, 30, 30); 
    day = Color.white; 

    childSpriteRenderers = transform.GetComponentsInChildren<SpriteRenderer>(); 
    } 

    void Update() 
    { 
    DayNightCycle(); 
    } 

    void DayNightCycle() 
    { 
    if (Input.GetKey (KeyCode.Q)) 
    { 
     foreach (SpriteRenderer child in childSpriteRenderers) 
     { 
     child.color = Color.Lerp (child.color, night, Time.deltaTime); 
     } 
    } 

    if (Input.GetKey (KeyCode.E)) 
    { 
     foreach (SpriteRenderer child in childSpriteRenderers) 
     { 
     child.color = Color.Lerp (child.color, day, Time.deltaTime); 
     } 
    } 
    } 
} 
相關問題