-
Notifications
You must be signed in to change notification settings - Fork 23
Add a "Draw Behavior Tree" Button to the Inspector
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.
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.
Customizing the Inspector requires an Editor script. Here's how to create one:
- 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.
- Create a new C# script in the Editor folder and call it
YourMonoBehaviorEditor
. With the NPC Sample project I called my scriptNonplayerCharacterEditor
because it was customizingNonPlayerCharacter
. - Add the below code to the script and replace all references to
NonPlayerCharacter
with the actual class name that this editor script will support. - 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();
}
}
}
Behavior Tool Debugger was created by What Up Games, LLC. It is currently in beta.