Unity脚本中枚举类型在inspector面板中文显示,供大家参考,具体内容如下
效果:
工具脚本:ChineseEnumTool.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
using System; using UnityEngine; #if UNITY_EDITOR using UnityEditor; using System.Reflection; using System.Text.RegularExpressions; #endif /// <summary> /// 设置枚举名称 /// </summary> #if UNITY_EDITOR [AttributeUsage(AttributeTargets.Field)] #endif public class EnumAttirbute : PropertyAttribute { /// <summary> /// 枚举名称 /// </summary> public string name; public EnumAttirbute( string name) { this .name = name; } } #if UNITY_EDITOR [CustomPropertyDrawer( typeof (EnumAttirbute))] public class EnumNameDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { // 替换属性名称 EnumAttirbute enumAttirbute = (EnumAttirbute)attribute; label.text = enumAttirbute.name; bool isElement = Regex.IsMatch(property.displayName, "Element \\d+" ); if (isElement) { label.text = property.displayName; } if (property.propertyType == SerializedPropertyType.Enum) { DrawEnum(position, property, label); } else { EditorGUI.PropertyField(position, property, label, true ); } } /// <summary> /// 重新绘制枚举类型属性 /// </summary> /// <param name="position"></param> /// <param name="property"></param> /// <param name="label"></param> private void DrawEnum(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginChangeCheck(); Type type = fieldInfo.FieldType; string [] names = property.enumNames; string [] values = new string [names.Length]; while (type.IsArray) { type = type.GetElementType(); } for ( int i = 0; i < names.Length; ++i) { FieldInfo info = type.GetField(names[i]); EnumAttirbute[] enumAttributes = (EnumAttirbute[])info.GetCustomAttributes( typeof (EnumAttirbute), false ); values[i] = enumAttributes.Length == 0 ? names[i] : enumAttributes[0].name; } int index = EditorGUI.Popup(position, label.text, property.enumValueIndex, values); if (EditorGUI.EndChangeCheck() && index != -1) { property.enumValueIndex = index; } } } #endif public class ChineseEnumTool : MonoBehaviour { } |
新建Text脚本测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
using System.Collections; using System.Collections.Generic; using UnityEngine; //定义动物类 public enum Animal { [EnumAttirbute( "小狗" )] dog, [EnumAttirbute( "小猫" )] cat, [EnumAttirbute( "老虎" )] tiger } public class Test : MonoBehaviour { [EnumAttirbute( "动物" )] public Animal animal; void Start () { } void Update () { } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_42345116/article/details/113944092