Skip to content

BehaviourButton

Matheus Lessa Rodrigues edited this page Feb 2, 2018 · 7 revisions

BehaviourButton

If you need to execute a piece of code while in Unity Editor, you can simply put the attribute [Button] above a function. Doing that, a button will show on its inspector and clicking it will run that function.

using UnityEngine;
using BitStrap;

public sealed class MyScript : MonoBehaviour
{
    [Button]
    public void SomeFunction()
    {
        Debug.Log( "Hello!" );
        // Some code here!
    }
}

With this sample code, MyScript's inspector will look like:

BehaviourButton

By pressing the Some Function button, Hello! will be print on the console and whatever other code you put there, will also execute.

Important

Note, however, that the [Button] attribute won't work with custom editors! When writing custom editors, you can call ButtonAttributeHelper.DrawButtons() to draw it wherever you want, tho.

using UnityEngine;
using UnityEditor;
using BitStrap;

[CustomEditor( typeof( MyScript )]
public sealed class MyCustomEditor : Editor
{
     private ButtonAttributeHelper helper = new ButtonAttributeHelper();

     public override void OnInspectorGUI()
     {
          base.OnInspectorGUI();
          helper.DrawButtons();
     }

     private void OnEnable()
     {
          helper.Init( target );
     }
}
Clone this wiki locally