Referencing Scene Objects

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

As you are testing you find that everything is working well and now you’d like to make a prefab out of it so you can have multiple agents in your scene. As soon as you make the agent a prefab and remove it from the scene you’ll find that the Target Object reference has gone missing. The reason this occurs is because as a project level asset (the prefab, or global variables file) cannot reference objects in the scene. This is a Unity restriction and the way to overcome it is to populate the variable at runtime after you have spawned the prefab.

The scene reference object can be populated at runtime in many different ways. One way is to use the Find task and search for the object by name:

 

When the Find task runs it’ll search for a GameObject named “Enemy” and then place it in a SharedVariable. When Can See Object runs it’ll then use that SharedVarible to search for the target object.

Another way to populate the value at runtime is to have a component already in the scene which has a reference to the object. After the prefab has been spawned this component can then set the value of a SharedVariable that the Can See Object uses.

using UnityEngine;
using BehaviorDesigner.Runtime;

public class Spawner : MonoBehaviour
{
    public GameObject m_Enemy;

    public void Start()
    {
        var behaviorTree = GetComponent<BehaviorTree>();
        behaviorTree.SetVariableValue("Enemy", m_Enemy);
    }
}