【问题标题】:Enum outside class in Unity C#Unity C#中的枚举外部类
【发布时间】:2016-07-04 08:49:54
【问题描述】:

我正在创建一个脚本来管理 Unity3D 中 UI 元素的淡入淡出,但有时我会遇到枚举问题

前几天我看到一个非常酷的让元素褪色的资产,并决定对其进行逆向工程

经过一段时间研究教程和阅读此页面中的问题后,我在使用枚举时遇到了困难,我不知道如何从其他类访问我的枚举,所以我想寻求帮助

我使用的是 Unity 版本 5.3.5f1

目标

  • 在 Unity 中淡化 UI 元素(图像、按钮等)
  • 通过脚本淡化
  • 使用枚举来做到这一点
  • 访问类外的枚举

如何重现它

  • 新的 Unity 项目(不管是 2D 还是 3D)

  • 空游戏对象

  • UI 元素(图片)

  • 图像填充屏幕并随机显示其颜色(任何颜色)

  • 新的C#脚本,我称之为Test

完成

  • 了解枚举
  • 带枚举的基本类

C#代码

这是我的代码(到目前为止)

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()
  {
  }
}

我会很高兴阅读好的解释和不友好的答案

谢谢

【问题讨论】:

  • 首先FadeOperations是一个类。所以你创建了对象数组。您可以像这样在单个对象中访问您的枚举:fadeOperations[0].fadeType 如果数组不是null
  • 您需要将枚举 FadeManager 移到类块之外,然后才能访问它

标签: c# class unity3d enums


【解决方案1】:

从技术上讲,如果您在类中声明枚举,则该枚举充当嵌套类。

因此,使用您目前拥有的代码库,您需要在 FadeOperations 之外引用 FadeManager,如下所示:

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

  public FadeOperations[] fadeOperations;

  private void Start()
  {
  }
}

但是,您可能会发现将枚举移到 FadeOperations 类之外更实用:

public enum FadeManager
{
    fadeIn,
    fadeOut
};

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

然后你直接访问FadeManager 类,通过它的名字,在FadeOperations 和其他类似的类中。

由您决定哪个更适合您。

【讨论】:

  • 这个答案似乎是合法的,枚举的行为会像以前一样吗??
  • 是的,它在两种情况下的行为都是一样的,除了在第一种情况下,您必须将其称为 FadeOperations.FadeManager(在 FadeOperations 上下文之外时)而不是仅仅 FadeManager
  • 我试试
  • 谢谢它像魅力一样工作......但现在我有一个新问题,我的代码逻辑工作到一半,代码只检查枚举的 1 个元素,无论我使用 switch 还是if 它只检测第一条语句
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 2014-10-30
  • 1970-01-01
  • 2010-11-26
  • 2012-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多