Example Behavior Tree in Unity Behave

Here is the Behavior Tree I used for the Lizard Enemy in the “Lizards” game demo. In some respects it’s kind of like a graphically modeled version of scripted if-then-else statements. And honestly, for this small of a project, it may have been better to use a mess of if-then-else statements. But it’s nice that there’s a bit more scalability to this approach. I can reuse these trees easily for different enemies and keep expanding the tree with more complex behaviors.

Two key elements I found very useful to have were the Check action and ExitIf Decorator. Check just returns success or failure if its given string expression is true or false. ExitIf is pretty much the same thing, but in the reverse. It returns failure if true and success if false, thus exiting out of a subtree if the condition is met. There’s a little bit of reflection magic here, but your expressions are still limited to (&&,||, and !). See the code for this below.

Lizard Root Tree:

Patrol Tree:

EvaluateExpression Snippet:

private bool EvaluateExpression( string expr ) {
    string[] exprs;
    exprs = expr.Split( new string[] { "&&"} , System.StringSplitOptions.None );
    if( exprs.Length > 1 ) {
        foreach( string e in exprs ) {
            if( !EvaluateExpression( e.Trim() ) ) {
                return false;
            }
        }
        return true;
    } else {
        exprs = expr.Split( new string[] { "||" }, System.StringSplitOptions.None );
        if( exprs.Length > 1 ) {
            foreach( string e in exprs ) {
                if( EvaluateExpression( e.Trim() ) ) {
                    return true;
                }
            }
            return false;
        } else {
            bool not = false;
            if( expr.StartsWith( "!" ) ) {
                not = true;
                expr = expr.Replace( "!" , "" );
            }
            bool b = (bool)this.GetType().GetProperty( expr ).GetValue( this  , null );
            if( not ) {
                return !b;
            } else {
                return b;
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Advertisements
%d bloggers like this: