How to Develop a Game
Attribute in Unity
PublishDate: 2025-06-01 | CreateDate: 2025-06-01 | LastModify: 2025-06-01 | Creator:ljf12825

Unity中的特性用于控制Unity编译器的行为,或者用于运行时特定的逻辑

Unity中常见特性

Unity为许多常见的操作都提供了特性

  1. SerializeField
[SerializeField]
private int playerHealth;
  1. HideInInspector
[HideInInspector]
public int secretValur;
  1. Range
[Range(0, 100)]
public int speed;
  1. Head
[Header("Player Settings")]
public float speed;
public int health;
  1. Tooltip
[Tooltip("Player's health value")]
public float health;
  1. ExecuteInEditMode
[ExecuteInEditMode]
public class CustomEditorScript : MonoBehaviour
{
    void Update()
    {
        // 在编辑模式下也会执行
    }
}
  1. ContextMenu
[ContextMenu("Reset Health")]
public void ResetHealth()
{
    health = 100;
}
  1. FormerlySerializedAs
[FormerlySerializedAs("oldPlayerHealth")]
[SerializeField]
private int health;
  1. DisallowMultipleComponent
[DisallowMultipleComponent]
public class MainCamera : MonoBehaviour{}
  1. RequireComponent
[RequireComponent(typeof(Rigidbody))]
public class Player : MonoBehaviour {}
  1. HideFlags
gameObject.hideFlags = HideFlags.HideInHierarchy;
  1. MenuItem
[MenuItem("Tools/Custom Action")]
public static void CustomAction() => Debug.Log("Custom action executed!");

13.Obsolete

[Obsolete("This method is obsolete. Use NewMethod() instead.")]
public void OldMethod() {}