Attribute feature of Unity editor extension (2)

The content will be continuously updated, please correct me if there are any errors, thank you!
 

Attribute feature of Unity editor extension (2)
     
TechX insists on bringing innovative technology to the world!

Have a better learning experience - keep working hard, keep improving, keep exploring
TechX ——Heart for exploration and heart for progress!

Helps you quickly master the Attribute editor extension,

saving valuable learning time for beginners and avoiding confusion!

Attribute feature of Unity editor extension (1)

Attribute feature of Unity editor extension (2)

Attribute feature of Unity editor extension (3)

Attribute feature of Unity editor extension (4)


Preface:

  Unity attributes are .NET attributes used to decorate (mark) classes, fields, methods, and properties to control the behavior of the Unity engine, check code validity, and provide additional editor functionality. Unity features help developers better customize and control the behavior of game objects, components, editor interfaces, and other Unity-related elements.

Insert image description here



1. AddComponentMenu

AddComponentMenuUsed to customize the position of scripts displayed in the Unity Editor's Component menu.
This feature allows you to add scripts to specific menu paths to better organize your custom components.

In Unity, normally all scripts you create will appear in the "Component/Scripts" menu. This can lead to menus that become cluttered, especially in complex projects. To solve this problem, you can use AddComponentMenuattributes to categorize and organize your scripts.

Here is an AddComponentMenuexample of a feature:

using UnityEngine;

[AddComponentMenu("MyScripts/CustomScript")]
public class MyComponent : MonoBehaviour
{
    
    
   // 这是你的脚本的内容
}

In this example, AddComponentMenuthe property adds the script MyComponent to the MyScripts submenu of the Component menu and names it CustomScript. In the Unity Editor, you will see a menu called "MyScripts" which contains the "CustomScript" option. This makes it easier for you to find and add your custom scripts.

Insert image description here



二、DisallowMultipleComponent

DisallowMultipleComponentUsed to prevent multiple components of the same type from being added to the same GameObject.

When you add this attribute to a script class, Unity will ensure that only one component of that script type can be added to the same GameObject.

The main purpose of this feature is to help developers avoid accidentally adding multiple components of the same type on the same GameObject, as this can lead to unpredictable behavior and bugs. By using DisallowMultipleComponentthe attribute, you can ensure that there is only one component of a specific type on each GameObject.

Here is an DisallowMultipleComponentexample of a feature:

using UnityEngine;

[DisallowMultipleComponent]
public class MyComponent : MonoBehaviour
{
    
    
   // 这是你的脚本的内容
}

In the above example, the MyComponent script is marked as DisallowMultipleComponent, which means you cannot add multiple MyComponent components to the same GameObject.

Insert image description here



三、RequireComponent

RequireComponent Used to ensure that components of a specific type exist together on the same GameObject.

This feature is often used to help developers avoid forgetting to add required components on a GameObject.

When you RequireComponentadd attributes to a script class, you can specify one or more required component types. If the script class is attached to a GameObject but the specified components are missing, Unity will automatically add these required components to ensure that the GameObject has the correct component configuration.

Here is an RequireComponentexample of a feature:

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class MyComponent : MonoBehaviour
{
    
    
    // 这个脚本需要一个 Rigidbody 组件
    // 如果 GameObject 上没有 Rigidbody 组件,Unity 会自动添加一个
}

In the above example, the MyComponent script is marked as RequireComponentand the Rigidbody component is specified as a required component. This means that if you add the MyComponent component to a GameObject, but the GameObject does not have a Rigidbody component, Unity will automatically add a Rigidbody component to meet the required conditions.

Insert image description here



4. MenuItem

MenuItemUsed to add custom menu items to the menu bar of the Unity editor.

This allows developers to create custom editor tools, shortcuts, or functions and integrate them into the Unity Editor to increase productivity.

The MenuItem attribute has two common uses:

  1. Open a script or scene file: Developers can create MenuItema menu item that allows them to easily open a script file or scene file without having to manually navigate to the assets panel or file assets.
  2. Execute custom functions: MenuItemDevelopers can create custom functions such as automated workflows, cleanup actions, or custom editor tools. These functions can be triggered through menu items, making the Unity Editor more powerful and easier to use.

Here are MenuItemexamples of feature usage:

using UnityEngine;
using UnityEditor;

public class MyCustomEditor : Editor
{
    
    
    [MenuItem("MyTools/Open Script Folder")]
    public static void OpenScriptFolder()
    {
    
    
        // 打开脚本文件夹
        EditorUtility.RevealInFinder(Application.dataPath);
    }

    [MenuItem("MyTools/Custom Editor Tool")]
    public static void CustomEditorTool()
    {
    
    
        // 执行自定义编辑器工具的操作
        // 可以是任何自定义功能
    }
}

In the above example, we MenuItemcreated two menu items for the custom editor class using attributes.

The first menu item "Open Script Folder" can open the script folder.

The second menu item "Custom Editor Tool" performs the operations of the custom editor tool.

MenuItemThe property accepts a menu path as an argument, which specifies under which menu in the Unity Editor the menu item should appear.

Developers can use slashes / to separate submenus of menu items. If necessary, you can also use shortcut keys, such as "MyTools/Open Script Folder %&O", where % represents the Ctrl key, & represents the Alt key, and # represents the Shift key.

Insert image description here



5. ContextMenu

ContextMenuUsed to add a context menu for a component or script in the Inspector window.

Using this feature, you can create custom menu items on components or scripts in the Inspector to execute these methods when editing.

This feature is typically used for custom editor extensions to provide additional tools or convenient functionality. For example, you can add a context menu item to a method in a script that, when clicked, triggers method execution to perform a specific task.

Here are ContextMenuexamples of feature usage:

using UnityEngine;
using UnityEditor;

public class MyComponent : MonoBehaviour
{
    
    
    [ContextMenu("Do Something")]
    private void MyCustomMethod()
    {
    
    
        // 当在 Inspector 中的上下文菜单中选择 "Do Something" 时,将触发这个方法。
        Debug.Log("Doing something...");
    }
}

In this example, the [ContextMenu("Do Something")] attribute is applied to the MyCustomMethod method, which creates a context menu item named "Do Something" in the Inspector. When the user selects the menu item in the Inspector, the execution of the MyCustomMethod method will be triggered.

Insert image description here



六、ContextMenuItemAttribute

ContextMenuItemAttributeUsed to add custom context menu items for fields or properties in the Inspector window.

You can apply this feature on custom fields to add custom context menu items for them in the Inspector window of the Unity editor. These menu items perform specific actions while editing.

Here are ContextMenuItemAttributeexamples of feature usage:

using UnityEngine;

public class MyComponent : MonoBehaviour
{
    
    
    [ContextMenuItem("Reset Score", "ResetScore")]
    public int playerScore;

    private void ResetScore()
    {
    
    
        playerScore = 0;
    }
}

In this example, the [ContextMenuItem(“Reset Score”, “ResetScore”)] attribute is applied to the playerScore field.

This will create a context menu item for the playerScore field in the Inspector that will read "Reset Score" when right-clicking on the field.

When the user selects this menu item in the Inspector, the ResetScore method will be triggered, which resets the playerScore to 0.

Insert image description here



七、CreateAssetMenuAttribute

CreateAssetMenuAttributeUsed to create custom resource menu items for scripts in the Unity Editor.

This feature allows you to create new custom resources, such as instances of scripts or configuration files, under the "Assets" menu.

You can CreateAssetMenuAttributeapply attributes to your custom script classes to easily create new resource instances in the Unity Editor. This is useful for generating custom profiles, materials, textures, etc.

Here are CreateAssetMenuAttributeexamples of feature usage:

using UnityEngine;
using UnityEditor;

[CreateAssetMenu(fileName = "NewSettings", menuName = "MyGame/PlayerSettings")]
public class PlayerSetting : ScriptableObject
{
    
    
    public string playerName;
    public int playerScore;
}

In this example, the [CreateAssetMenu] attribute is applied to the PlayerSetting class.

This attribute specifies the new asset's file name (fileName) and location under the "Assets" menu (menuName).

In the Unity Editor, you can now create a new PlayerSetting resource instance by clicking on the "Assets" menu and selecting "Create" > "MyGame" > "PlayerSettings".

Insert image description here



八、RuntimeInitializeOnLoadMethodAttribute

RuntimeInitializeOnLoadMethodAttributeUsed to mark static methods, which are automatically called when Unity is initialized during runtime.

Typically, this feature is used to perform some initialization logic or register callback functions when the game starts.

To use RuntimeInitializeOnLoadMethodAttributethe attribute, you need to write a static method and apply the attribute to that method. Unity will automatically call methods with this attribute when your game starts.

Here are RuntimeInitializeOnLoadMethodAttributeexamples of feature usage:

using UnityEngine;

public class MyInitializer
{
    
    
    [RuntimeInitializeOnLoadMethod]
    static void InitializeOnLoad()
    {
    
    
        // 在游戏启动时执行的初始化逻辑
        Debug.Log("Game is starting, performing initialization...");
    }
}

In the above example, the InitializeOnLoad method is RuntimeInitializeOnLoadMethodmarked with attribute so it will be executed when the game starts. Within this method you can perform any initialization work you need to do when the game starts.

This feature is usually used to perform certain global initialization operations when the project starts, such as setting the initial state of the game, loading configuration, registering global events, etc. This ensures that these actions are performed automatically when the game starts without requiring manual triggering.



九、DelayedAttribute

DelayedAttributeUsed to mark fields, telling Unity to delay applying the field's value in the editor.

This feature is typically used when a value needs to be applied later or at a specific time.

When you adjust a field with the Delayed attribute in the Inspector, Unity does not apply the changes immediately but waits until the editor's "Update" frame. This allows you to optimize between changing field values ​​multiple times to avoid frequent recalculations or resource loads.

using UnityEngine;

public class MyComponent : MonoBehaviour
{
    
    
    [Delayed]
    public float delayedValue = 0.0f;

    private void Update()
    {
    
    
        // 这里的 delayedValue 可能在多次更改后才会应用
        Debug.Log("Delayed Value: " + delayedValue);
    }
}

In the above example, the delayedValue field is marked DelayedAttribute. When you change its value in the Inspector, Unity does not apply the change immediately, but waits until the Update method is called on the next frame. This helps make value adjustments in the editor without triggering too many recalculations.

DelayedAttributeThe attribute is useful for tweaking and testing the behavior of numeric fields, as it allows you to get better feedback when making multiple fine-tunings without triggering expensive operations after each change.





TechX ——Heart for exploration and heart for progress!

Every fall is a growth,

every effort is a progress

END
Thank you for reading this blog! Hope this content is helpful to you. If you have any questions or comments, or would like to know more about this topic, please feel free to leave a message in the comment area to communicate with me. I will be more than happy to discuss and share more interesting content with you all.
If you like this blog, please like and share it with more friends so that more people can benefit. In the meantime, you can also follow my blog to get the latest updates and articles in a timely manner.
In future writing, I will continue to work hard to share more interesting and practical content. Thank you again for your support and encouragement, and I look forward to seeing you in the next blog!

Guess you like

Origin blog.csdn.net/caiprogram123/article/details/133863290