簡體   English   中英

如何使switch語句與枚舉一起使用? C#Unity

[英]How can I make a switch statement work with an enum? C# Unity

描述

我正在使用腳本來淡化Unity中的UI元素,類似於選擇器,您可以在其中選擇淡出的類型,持續時間和要淡入的圖像

在此處輸入圖片說明

我發現,枚舉是實現這一結果的最佳選擇,但我有一個問題,當我運行的代碼只有枚舉工作的元素和其他不這樣做,無論我是否使用switch或者if只是第一個語句運行,我不知道代碼有什么問題

  • 請解釋你的答案
  • 請解釋為什么代碼錯誤
  • 請提供有關如何改進的反饋

我正在使用Unity版本5.3.5f1和Visual Studio Community 2015

目標

  • 使枚舉正常工作使用任何switchif
  • 能夠使用FadeOperations類中的變量在Test類中進行計算
  • 從數組中選擇所需操作的類型
  • 從Heriarchy中選擇一個UI元素並將其淡入

腳步

  • 創建新的Unity項目(2D或3D)
  • 創建UI圖像
  • 創建空游戲對象
  • 創建新的C#腳本(我稱它為Test)
  • 將新腳本附加到空游戲對象

這是我的代碼...

using UnityEngine;
using UnityEngine.UI;

 public enum FadeManager
 {
     fadeIn,
     fadeOut
 };

 [System.Serializable]
 public class FadeOperations
 {
     [Tooltip("Type of fading")]
     public FadeManager fadeType;

     [Tooltip("Duration time of the fading")]
     public float duration;

     [Tooltip("Select the image to fade")]
     public Image fadeImage;
 }

 public class Test : MonoBehaviour
 {
     [Tooltip("Select your type of fade")]
     public FadeOperations[] fadeOperations;

     //Reference to the class FadeOperations
     private FadeOperations _fo = new FadeOperations();

     //Loop for debug
     private void Start()
     {
         Debug.Log(_fo.fadeType);
         switch (_fo.fadeType)
         {
             //This statement works
             case FadeManager.fadeIn:
                 Debug.Log("Fadein"); //Only this piece of code works
                 break;

             //This statement doesn't work
             case FadeManager.fadeOut:
                 Debug.Log("Fadeout");
                 break;
         }
      }
  }

switch前的Log (_fo.fadeType)結果

fadeIn
UnityEngine.Debug:Log(Object)
Test:Start() (at Assets/_Scripts/Test.cs:34)

您可能要執行以下操作:

public class Test : MonoBehaviour
{
    [Tooltip("Select your type of fade")]
    public FadeOperations[] fadeOperations;

    //Loop for debug X  NOTE: Start method runs only one time.dont expect it to run it for multiple time 
    private void Start()
    {
        foreach(var operation in fadeOperations)
        {
            Debug.Log(operation.fadeType);
            switch (operation.fadeType)
            {
                case FadeManager.fadeIn:
                    Debug.Log("Fadein"); // write your fading in code here
                    break;

                case FadeManager.fadeOut:
                    Debug.Log("Fadeout"); // write your fading out code here
                    break;
            }
        }
     }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM