Understand why scene references disappear

As you are creating your tree it is common practice to reference objects within the scene from a Shared Variable or task. For example, use the Can See Object to determine if the Enemy GameObject can be seen:

A Can See Object task references an Enemy GameObject from the current scene.

As you are testing, you may make the agent a prefab so it can be reused. When that prefab is removed from the scene, its Enemy reference goes missing because project assets—including prefabs, subtrees, and project variables—cannot reference scene objects.

Assign the reference at runtime

Populate the scene reference at runtime in one of these ways:

  • Add a task to your behavior tree which searches for the object. This can be done with something as basic as the GameObject.Find method or your own retrieval system.
  • Add the Behavior Tree component to your scene and use Variable Overrides to override the subtree variable value.
  • Assign the variable value through your own initialization script.

The Runtime Behavior and Subtrees sample scenes shows an example of using overrides. Each method has their own advantages and disadvantages so there’s no one right way to assign the scene value.