简体   繁体   中英

Enum outside class in Unity C#

I'm creating a script to manage the fading of UI elements in Unity3D, and at some point I'm stuck with enums

The other day I saw a very cool asset to fade elements, and decided to reverse engeneer it

After some time researching with tutorials and reading questions in this page, I got stuck using the enums, I don't know how to access my enum from another class so I want to ask for help

I'm using Unity version 5.3.5f1

Goal

  • Fade UI elements in Unity (Images, buttons, etc)
  • Fade via script
  • Use of enums to do it
  • Acces enums outside a class

How to reproduce it

  • New Unity project (doesn't matter 2D or 3D)

  • Empty gameobject

  • UI element (image)

  • Image fill screen and chance its color (any color)

  • New C# script, I called it Test

Done

  • Read about enums
  • Basic class with enum

Code C#

Here's my code (so far)

using UnityEngine;
using UnityEngine.UI;

[System.Serializable]
public class FadeOperations
{
   public enum FadeManager
{
    fadeIn,
    fadeOut
};

  [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
{
  //Where do I acces the enum inside this class??

  //This is the variable for the inspector to see the elements inside the other class
  public FadeOperations[] fadeOperations;

  private void Start()
  {
  }
}

I'll be glad to read good explanations and noobfriendly answers

Thanks

Technically speaking, if you declare an enum inside a class, that enum acts as the nested class.

So, with the codebase you have at the moment, you would need to refer to FadeManager outside FadeOperations like here:

public class Test : MonoBehaviour
{
  // the variable of FadeManager type outside FadeOperations
  public FadeOperations.FadeManager fadeManager;

  public FadeOperations[] fadeOperations;

  private void Start()
  {
  }
}

However, you might find it more practical to move the enum outside the FadeOperations class instead:

public enum FadeManager
{
    fadeIn,
    fadeOut
};

[System.Serializable]
public class FadeOperations
{
    //FadeOperations body goes here...
}

Then you access the FadeManager class directly, by its name, in FadeOperations and other classes alike.

It's up to you to decide which works better for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM