Writing a New Conditional Task
A Conditional observes game state and returns Success or Failure without
performing the behavior itself. This example finds a tagged object inside the
agent’s field of view and writes it to a shared variable.
Create the task
Add a runtime C# script that derives from Conditional. Public
SharedVariable fields can use either constants or Variables-panel bindings.
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;
using UnityEngine;
[TaskCategory("Tutorial")]
[TaskDescription("Succeeds when a tagged object is inside the field of view.")]
public class WithinSight : Conditional
{
public SharedFloat FieldOfViewAngle = 90f;
public SharedString TargetTag;
public SharedTransform Target;
private GameObject[] possibleTargets;
public override void OnStart()
{
possibleTargets = GameObject.FindGameObjectsWithTag(TargetTag.Value);
Target.Value = null;
}
public override TaskStatus OnUpdate()
{
for (int i = 0; i < possibleTargets.Length; ++i) {
var candidate = possibleTargets[i].transform;
var direction = candidate.position - transform.position;
if (Vector3.Angle(direction, transform.forward) < FieldOfViewAngle.Value) {
Target.Value = candidate;
return TaskStatus.Success;
}
}
return TaskStatus.Failure;
}
public override void OnReset()
{
FieldOfViewAngle = 90f;
TargetTag = string.Empty;
Target = null;
}
}
OnStart refreshes the candidates each time traversal enters the task.
OnUpdate returns Success as soon as one candidate qualifies and Failure when
none do. For large or frequently changing target sets, replace the tag search
with a dedicated sensing system and expose its result to the task.
Add it to a tree
- Allow Unity to compile.
- In the Tasks panel, add Tutorial > Within Sight below a Sequence.
- Set Target Tag and Field Of View Angle.
- Create a local
Transformvariable namedTargetand bind the output field
to it. - Add a task after the Conditional that consumes
Target.
Verify the result
Enter Play Mode with one correctly tagged object in front of the agent. The
Conditional should return Success and Target should contain that Transform.
Move the object outside the angle and restart the branch; it should return
Failure.
Continue with Writing a New Action Task to
consume the target. See Tasks for the lifecycle and
Task Attributes for editor presentation.