Skip to content

Add a "Draw Behavior Tree" Button to the Inspector

Stacey edited this page Oct 6, 2020 · 3 revisions

This quick guide will walk you through how to add a button on the Inspector window so that you can trigger the drawing of a behavior tree in the tool. To illustrate a 'real world' example, this guide will reference the implementation for the NPC Sample project - specifically the NonPlayerCharacter script. You can also skip this guide and look at the runtime and editor scripts for reference.

Add the method for drawing the Behavior Tree

Your MonoBehavior class will need a public method that can be called from the Editor script. Add the following C# method to your class:

public void ForceDrawingOfTree()
{
    if (BehaviorTree == null)
    {
        $"Behavior tree is null - nothing to draw.".BTDebugLog();
    }
    //Tell the tool to draw the referenced behavior tree. The 'true' parameter tells it to give focus to the window. 
    BehaviorTreeGraphWindow.DrawBehaviorTree(BehaviorTree, true);
}    

Note: The above code assumes you have already implemented the IBehaviorTree interface. If you have not setup your project to work with the Behavior Tree tool, head over to Getting started with an existing behavior tree implementation.

Create the editor script

Customizing the Inspector requires an Editor script. Here's how to create one:

  1. Within your Assets folder, create a new Editor folder. This can be located any where, though I like to nest it under my Scripts folder, making the path Assets/Scripts/Editor.
  2. Create a new C# script in the Editor folder and call it YourMonoBehaviorEditor. With the NPC Sample project I called my script NonplayerCharacterEditor because it was customizing NonPlayerCharacter.
  3. Add the below code to the script and replace all references to NonPlayerCharacter with the actual class name that this editor script will support.
  4. Replace the m_NPC.ForceDrawingOfTree() with the method that you created earlier.
//Tells Unity which class this editor script is targeting
[CustomEditor(typeof(NonPlayerCharacter))]
public class NonplayerCharacterEditor : UnityEditor.Editor
{
    //Store a reference to the instance of the class
    private NonPlayerCharacter m_NPC;

    private void OnEnable()
    {
        //Get the reference to the instance of the class
        m_NPC = target as NonPlayerCharacter;

        EditorApplication.update += RedrawView;
    }

    void RedrawView()
    {
        Repaint();
    }

    public override void OnInspectorGUI()
    {
        //Makes sure the original inspector is drawn. Without this the button would replace any serialized properties
        DrawDefaultInspector();

        //Create the button
        if (GUILayout.Button("Draw Behavior Tree"))
        {
            //The method that is run if the button is pushed
            m_NPC.ForceDrawingOfTree();
        }
    }
}
Clone this wiki locally