unity 自定义Attribute
时间: 2025-06-22 07:43:48 浏览: 21
### 创建和使用自定义属性
在 Unity 中,通过继承 `PropertyAttribute` 类并应用 `[AttributeUsage]` 特性来创建自定义属性。这允许开发者指定新特性可应用于哪些程序元素。
对于字段级别的自定义属性,代码如下所示:
```csharp
using System;
using UnityEngine;
[AttributeUsage(AttributeTargets.Field)]
public class SceneName : PropertyAttribute {
}
```
此段代码声明了一个名为 `SceneName` 的简单自定义属性[^2]。然而,在这个阶段,它仅作为标记存在,并不会影响 Inspector 行为或提供额外功能。
为了使自定义属性生效,还需要编写相应的编辑器脚本来处理带有特定属性的字段。通常涉及实现 `CustomPropertyDrawer` 或者直接操作 `SerializedObject` 和 `SerializedProperty` API 来控制显示逻辑。
下面是一个简单的例子展示如何绘制带有所述 `SceneName` 属性的字符串字段:
```csharp
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(SceneName))]
public class SceneNameDrawer : PropertyDrawer {
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
// 只针对 string 类型有效
if (property.propertyType != SerializedPropertyType.String) {
EditorGUI.LabelField(position, label.text, "Only works on strings!");
return;
}
// 获取当前场景名称列表
var scenes = EditorBuildSettings.scenes;
string[] options = new string[scenes.Length];
for(int i=0;i<scenes.Length;++i){
options[i]=System.IO.Path.GetFileNameWithoutExtension(scenes[i].path);
}
// 绘制下拉框控件
int selectedIndex = Mathf.Max(0,System.Array.IndexOf(options, property.stringValue));
selectedIndex = EditorGUI.Popup(position,label.text,options,selectedIndex);
// 更新目标对象上的值
property.stringValue = options[selectedIndex];
}
}
```
这段代码实现了对具有 `SceneName` 自定义特性的字段进行特殊渲染的功能——即从项目设置中的构建配置读取可用场景名,并呈现成一个方便的选择界面给用户交互。
当把以上两个组件结合起来时,便可以在 Unity 编辑器内看到更加友好直观的操作体验;同时保持了 C# 语法糖带来的灵活性与简洁度。
阅读全文
相关推荐




















