Unity学会使用高级功能Attributes(特性),让您的程序如虎添翼


在Unity中,Attributes用于增强类、字段、方法等程序元素的行为或元数据信息,这些信息可以在编辑器界面中或者通过代码反射来访问和使用。以下是如何在Unity中使用内置及自定义Attributes的示例说明:

使用内置Attributes例子

1. [SerializeField]

[SerializeField]
private int hiddenValue;

此Attribute允许将私有变量显示在Unity Inspector中,尽管它不是public。

2. [HideInInspector]

[HideInInspector]
public float hideInInspector;

使Inspector忽略该字段,不显示在编辑界面中。

3. [Range(min, max)]

[Range(0f, 1f)]
public float opacity;

对数值型字段添加范围限制,并在Inspector中以滑动条的形式呈现。

4. [Header(“Section Name”)]

[Header("Player Settings")]
public string playerName;
public int playerHealth;

在Inspector中为一系列属性创建标题分组。

5. [ExecuteInEditMode]

[ExecuteInEditMode]
public class CameraFollow : MonoBehaviour
{
    void Update()
    {
        // 这个脚本在编辑器非播放模式下也会执行Update方法
    }
}

标记一个MonoBehaviour使其在编辑器中的Edit Mode也能执行特定逻辑。

自定义并使用Attributes例子

示例1 自定义Attribute

首先,定义一个自定义Attribute:

using System;

public class CustomTagAttribute : PropertyAttribute
{
    public string TagName { get; set; }

    public CustomTagAttribute(string tagName)
    {
        TagName = tagName;
    }
}

然后,创建一个对应的PropertyDrawer以在Inspector中展示效果:

using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(CustomTagAttribute))]
public class CustomTagPropertyDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        var tagAttr = attribute as CustomTagAttribute;
        EditorGUI.LabelField(position, $"{label.text} ({tagAttr.TagName})");
        // 根据需要实现自定义绘制逻辑
    }

    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        return EditorGUI.GetPropertyHeight(property);
    }
}

最后,在Unity脚本中使用自定义Attribute:

public class MyScript : MonoBehaviour
{
    [CustomTag("Important Field")]
    public int myIntegerField;
}

现在,myIntegerField将在Inspector中显示时带有额外的信息“Important Field”。注意,对于这个自定义Attribute,我们还需要为其编写对应的PropertyDrawer来真正地改变Inspector中的显示方式。上述例子简化了PropertyDrawer的实现,实际应用中可能需要更复杂的操作来修改Inspector样式或行为。

示例2:创建一个自定义Attribute

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class CustomAuthorAttribute : Attribute
{
    public string AuthorName { get; set; }
    public string Version { get; set; }

    public CustomAuthorAttribute(string author, string ver)
    {
        AuthorName = author;
        Version = ver;
    }
}

上述代码定义了一个名为CustomAuthorAttribute的自定义Attribute,它可以应用于类或方法上,并带有作者名称和版本信息。

示例3:使用自定义Attribute

[CustomAuthor("John Doe", "1.0")]
public class MyClass
{
    // 类的成员...
}

[CustomAuthor("Jane Smith", "2.1")]
public void MyMethod()
{
    // 方法体...
}

这里,我们已经在MyClass类和MyMethod方法上应用了CustomAuthorAttribute,分别指定了作者和版本信息。

示例4:通过反射获取自定义Attribute信息

Type myType = typeof(MyClass);
var attributes = myType.GetCustomAttributes(typeof(CustomAuthorAttribute), true);

if (attributes.Length > 0)
{
    CustomAuthorAttribute attr = (CustomAuthorAttribute)attributes[0];
    Console.WriteLine($"Class '{myType.Name}' was authored by {attr.AuthorName}, version: {attr.Version}");
}

MethodInfo methodInfo = myType.GetMethod(nameof(MyMethod));
var methodAttributes = methodInfo.GetCustomAttributes(typeof(CustomAuthorAttribute), true);

if (methodAttributes.Length > 0)
{
    CustomAuthorAttribute methodAttr = (CustomAuthorAttribute)methodAttributes[0];
    Console.WriteLine($"Method 'MyMethod' was authored by {methodAttr.AuthorName}, version: {methodAttr.Version}");
}

这个示例展示了如何通过反射技术从类和方法中获取并打印出它们所关联的CustomAuthorAttribute属性值。

python推荐学习汇总连接:
50个开发必备的Python经典脚本(1-10)

50个开发必备的Python经典脚本(11-20)

50个开发必备的Python经典脚本(21-30)

50个开发必备的Python经典脚本(31-40)

50个开发必备的Python经典脚本(41-50)
————————————————

​最后我们放松一下眼睛
在这里插入图片描述

  • 39
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 19
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极致人生-010

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值