Unity中常用的Attribute

本文详细介绍了Unity3D中常见的Attribute,包括HelpURLAttribute、RangeAttribute、RequireComponentAttribute、TooltipAttribute、HideInInspectorAttribute等,涵盖了从组件交互到Inspector面板显示的各种特性,帮助开发者更好地理解和利用Unity的元数据功能。
摘要由CSDN通过智能技术生成

前言:
在使用Unity3D的过程中,会经常用到许多的特性Attribute,我基本上把官方文档里列出的都记录下来,不定期更新

一、HelpURLAttribute
从字面意思理解,是查看帮助时,跳转到指定的页面。

如下图:

对应着蓝色小书的图标,点击以后会跳转到配置的URL。

二、RangeAttribute:限定int或float的取值范围。

Attribute used to make a float or int variable in a script be restricted to a specific range.
When this attribute is used, the float or int will be shown as a slider in the Inspector instead of the default number field.

当在int或float上应用RangeAttribute特性时,在Inspector面板中,显示的将是一个slider滑动条,而不是默认的数值字段。

[Range(0.1f,0.9f)]
float ratio;

三、RequireComponentAttribute

自动添加所要依赖的组件,如将一个Script做为一个GameObject的组件,而这个Script需要访问Rigidbody组件,
通过应用该属性,可以自动的添加Rigidbody组件到当前的GameObject中,避免设置错误。

*前提是:如果当前的Script已经添加到了GameObject,这时候你再应用RequireComponent特性是无效的,
你必须删除 再重新添加,才会检测。

using UnityEngine;

// PlayerScript requires the GameObject to have a Rigidbody component
[RequireComponent(typeof(Rigidbody))]
public class PlayerScript : MonoBehaviour
{
    Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        rb.AddForce(Vector3.up);
    }
}

四、TooltipAttribute
在Inspector面板中,为一个字段Field指定一个提示。

image.png

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    [Tooltip("Health value between 0 and 100.")]
    public int health = 0;
}

五、HideInInspectorAttribute

让一个可被序列化的字段,不要显示在Inspector面板中,防止修改。

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    [HideInInspector]
    public int p = 5;
}

六、ExecuteInEditMode

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值