Creating variables in the editor is useful when you need your AI to have preexisting knowledge of certain things. Maybe this is the location of their base, or several waypoint routes they should patrol, or where their team members are. It can also be useful for generic items that are used in Custom Actions that may change with each instantiation even though they use the same prefab (prefabs, assets, etc).
You can access any variables you create in Behavior Trees, Custom AI Elements, and in any MonoBehaviour through the AI Rig component.
If you are using a Custom Action, the Start
, Execute
, and Stop
functions are given an AI that they can use to access the memory and other elements.
using RAIN.Action; using RAIN.Core; using UnityEngine; [RAINAction] public class GetAmmo : RAINAction { public GetAmmo() { actionName = "GetAmmo"; } public override ActionResult Execute(AI ai) { // We don't check this because we assume the behavior tree did GameObject tAmmo = ai.WorkingMemory.GetItem<GameObject>("AmmoTarget"); SoldierAmmo tSoldierAmmo = tAmmo.GetComponent<SoldierAmmo>(); // If we already have ammunition, add to it if (ai.WorkingMemory.ItemExists("MyAmmo")) { SoldierAmmo tCurrentAmmo = ai.WorkingMemory.GetItem<SoldierAmmo>("MyAmmo"); tCurrentAmmo.IncreaseAmmo(tSoldierAmmo); } // Otherwise create it fresh else { SoldierAmmo tCurrentAmmo = new SoldierAmmo(); tCurrentAmmo.IncreaseAmmo(tSoldierAmmo); // You can't add custom components like SoldierAmmo in the RAIN editor, // but you can add them in code like this ai.WorkingMemory.SetItem<SoldierAmmo>("MyAmmo", tCurrentAmmo); } // Unspawn the ammo tSoldierAmmo.Unspawn(); return ActionResult.SUCCESS; } }
If you are not in a Custom Action node, you can still access and modify memory by going through the AI Rig.
using RAIN.Core; using UnityEngine; public class InitializeSoldier : MonoBehaviour { [SerializeField] SoldierAmmo _startingAmmo = null; void Start() { // Get our AI rig AIRig tRig = GetComponentInChildren<AIRig>(); // Our memory isn't on the rig itself, but in an AI object held by the rig if (_startingAmmo != null) tRig.AI.WorkingMemory.SetItem<SoldierAmmo>("MyAmmo", _startingAmmo); } }