在 Unity 编辑器开发中,我们常希望将枚举值转换为更友好的中文名称。例如在下拉菜单中显示 MoveInAnimation.Left 为 "左侧入场",而非直接显示枚举字面量。


// 定义枚举
public enum MoveInAnimation
{
    /// <summary>
    ///
    /// </summary>
    [InspectorName("无动画")]
    None,
    /// <summary>
    /// 淡入
    /// </summary>
    [InspectorName("淡入")]
    FadeIn,
    /// <summary>
    /// 从下往上滑入
    /// </summary>
    [InspectorName("从下滑入")]
    UnderSlideIn,
    /// <summary>
    /// 从左往右滑入
    /// </summary>
    [InspectorName("从左滑入")]
    LeftSlideIn,
    /// <summary>
    /// 从右往左滑入
    /// </summary>
    [InspectorName("从右滑入")]
    RightSlideIn
}

// 动态获取中文名称的流程
List<string> names = new();
foreach (MoveInAnimation value in Enum.GetValues(typeof(MoveInAnimation)))
{
    // 获取该枚举值的 MemberInfo
    MemberInfo[] memberInfo = value.GetType().GetMember(value.ToString());
    
    // 提取特性中的名称
    InspectorNameAttribute attr = memberInfo[0]
        .GetCustomAttributes(typeof(InspectorNameAttribute), false)
        .FirstOrDefault() as InspectorNameAttribute;
    
    // 优先使用特性名称,否则用原始名称
    names.Add(attr?.displayName ?? value.ToString());
}

以下是我的实际应用示例

            var moveinAnimationDropdown = new DropdownField("入场动画");
            List<string> moveinAnimations = new();
            foreach (MoveInAnimation type in Enum.GetValues(typeof(MoveInAnimation)))
            {
                // 获取枚举值的类型 获取中文名称
                var memberInfo = type.GetType().GetMember(type.ToString());
                if (memberInfo != null && memberInfo.Length > 0)
                {
                    var attrs = memberInfo[0].GetCustomAttributes(typeof(InspectorNameAttribute), false);
                    if (attrs.Length > 0)
                    {
                        var attr = attrs[0] as InspectorNameAttribute;
                        if (attr != null)
                        {
                            var name = attr.displayName;
                            moveinAnimations.Add(name);
                        }
                    }
                }
            }
            moveinAnimationDropdown.choices = moveinAnimations;
            moveinAnimationDropdown.value = moveinAnimations[(int)dialogueNode.ActorMoveInAnimationType];
            moveinAnimationDropdown.RegisterValueChangedCallback((e) =>
            {
                dialogueNode.ActorMoveInAnimationType = (MoveInAnimation)moveinAnimations.IndexOf(e.newValue);
            });
            moveinAnimationDropdown.style.marginBottom = 10f;
            AddElement(moveinAnimationDropdown);

Logo

盛京开源社区 SJOSC 官方论坛平台

更多推荐