[C#] Enum not working properly
Hello
I'm working on a script to fade UI elements in Unity, similar to a selector, where you can select the type of fading, and duration, and image to fade
My problem is when I run the code only one enum statement work and the other don't, no matter if I use switch
or if
just the first statement run, I don't know what's wrong with the code
Please explain your answer
Please explain how the code is wrong
Please give feedback on how to improve
I'm using Unity version 5.3.5f1 and Visual Studio Community 2015
Goal
Make the enum work properly using either
switch
orif
Be able to use the variables inside the FadeOperations class to make the calculations inside the Test class
Select from an array the type of desired operation
Select an UI element from Heriarchy and fade it
Code
Here's my code so far
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 Update()
{
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;
}
}
}
Answer by Dudicus · Jul 05, 2016 at 02:01 AM
You are trying to use a list as an enum. If you add [] at the end of the class name while declaring an instance it makes it a list. Remove that and change it to an enum. I don't know the actual code to make it a class an enum or even if that is possible but all the other lines of code should work.
If you become too stuck on this make a separate code for each GameObject.
I know I didn't answer your question but I hope it helps!!!
Answer by NoseKills · Jul 05, 2016 at 07:21 AM
When do you expect the other branch in the switch to trigger?
You make an instance of FadeOperations to a private field _fo
and that instance is what you are checking in the switch. That instance will always have the default value for fadeType since you don't change it anywhere.
private FadeOperations _fo = new FadeOperations();
private void Update()
{
switch (_fo.fadeType)
{...
If you want to check one of the FadeOperations instances to which you set a different fadeType to in the inspector, I believe you want to pull it from the public array you have (make sure you have at least one item in it)
private void Update()
{
switch (fadeOperations[0].fadeType)
{...