Skip to content

Method Button Attribute

Toto Christensen edited this page Nov 13, 2024 · 5 revisions

Overview

The [MethodButton] attribute enables direct method invocation from the Unity Inspector. This attribute is useful for testing methods directly within the inspector, making it handy for debugging, prototyping, or triggering certain actions both inside and outside of Play mode.

Capabilities

The [MethodButton] attribute supports the following capabilities:

  • Parameterized Methods: Methods with parameters can also be used, allowing you to specify default values in the [MethodButton] attribute.
  • Parameterless Method Support: Works with methods that do not require parameters.
  • Supported Parameter Types: Compatible with primitive types (e.g., int, float, bool), Unity native types (e.g., Vector3, GameObject), and custom serializable classes.
  • Dynamic Field Referencing: Enables you to reference other serialized fields as parameters.

Syntax and Examples

Note: These examples use Unity’s [SerializeField] on private fields to promote encapsulation. This approach can help protect internal data from unintended access by other scripts and maintain clean, organized code. For more details, see Unity’s documentation on SerializeField.

Applying [MethodButton] is straightforward. Add the attribute above the method you want to be accessible in the Inspector, and specify any parameters or field references as needed.

Basic Syntax

[MethodButton]
public void MethodName()
{
    // Method code here
}

Additional Constructor Syntax

// Set parameter expansion state
[MethodButton(false)]

// Method with specific parameters
[MethodButton(param1, param2, ...)]

// Method with parameter expansion state and specific parameters
[MethodButton(false, param1, param2, ...)]

Example 1: Using a Parameterless Method

In this example, LogMessage is a parameterless method that will display a message in the Console when invoked from the Inspector.

[MethodButton]
public void LogMessage()
{
    Debug.Log("Button clicked!");
}

Result: In the Inspector, a button labeled “Log Message” will appear, allowing you to trigger LogMessage by clicking the button.

Gif of Example 1 result

Example 2: Using a Method with Parameters (Inspector-Generated Inputs)

Here, SetPlayerStats is a method that requires an integer and a string as parameters. When [MethodButton] is applied to a method with parameters, Unity will automatically generate input fields for those parameters in the Inspector.

[MethodButton]
public void SetPlayerStats(int level, string playerName)
{
    Debug.Log($"Setting player stats: Level - {level}, Name - {playerName}");
}

Result: A button labeled “Set Player Stats” will appear in the Inspector, accompanied by input fields for the level and playerName parameters. You can enter values directly into these fields before pressing the button to invoke the method.

Gif of Example 2 result

Example 3: Using a Method with Parameters and Default Values

This example demonstrates a method PrintMessageMultipleTimes that takes a string message and an int specifying how many times the message should be printed. By specifying default values in [MethodButton], you set defaults for the parameters directly in the attribute.

[MethodButton("Hello World", 3)]
public void PrintMessageMultipleTimes(string message, int repeatCount)
{
    for (int i = 0; i < repeatCount; i++)
    {
        Debug.Log(message);
    }
}

Result: A button labeled “Print Message Multiple Times” will appear in the Inspector, and when clicked, it will print "Hello World" three times to the Console by default.

Gif of Example 3 result

Example 4: Using a Method with Field References as Parameters

In this example, ApplyDamage accepts a damage amount, which can be provided by referencing another serialized field (damageAmount) as the parameter.

[SerializeField]
private int damageAmount = 10;

[MethodButton("damageAmount")]
public void ApplyDamage(int amount)
{
    health -= amount;
    Debug.Log($"Damage applied: {amount}");
}

Result: A button labeled “Apply Damage” will appear in the Inspector. When clicked, it will execute ApplyDamage using the current value of damageAmount.

Gif of Example 4 result