Menu
Lumberyard
Developer Guide (Version 1.11)

Using Entity State

CryLua is deprecated and will be removed in a future version of Lumberyard.

Note

This page contains information on using Lua scripting to work with the legacy Entity system. These Lua scripts use the legacy script context. Starting with Lumberyard 1.8, Lua scripts use the new behavior context that replaces the legacy script context. Scripts that were written before the integration of the behavior context no longer work in Lumberyard versions 1.8 and later. For information on updating Lua code from legacy script context to the new behavior context, see the migration notes for Lumberyard 1.8. For information on using Lua with Lumberyard's new component entity system, see Writing Lua Scripts for the Component Entity System.

The Entity system provides a simple state-switching mechanism for script entities.

Each state consists of the following:

  • Name (string)

  • Lua table within the entity table, identified with the state name

  • OnEndState() function (optional)

  • OnBeginState() function (optional)

  • Additional callback functions (optional) (See Entity System Script Callbacks)

To declare states for an entity:

All entity states must be declared in the entity's main table to make the Entity system aware of them. The following examples show how to declare "Opened", "Closed", and "Destroyed" states.

Copy
AdvancedDoor = { Client = {}, Server = {}, PropertiesInstance = ... Properties = ... States = {"Opened","Closed","Destroyed"}, }

To define an entity state:

Entity states can be either on the server or client (or both). The definition for a server-side "Opened" state might look as follows:

Copy
AdvancedDoor.Server.Opened = { OnBeginState = function( self ) if(self.Properties.bUsePortal==1)then System.ActivatePortal(self:GetWorldPos(),1,self.id); end; self.bUpdate=1; self.lasttime=0; AI.ModifySmartObjectStates( self.id, "Open-Closed" ); self:Play(1); end, OnUpdate = function(self, dt) self:OnUpdate(); end, }

To set an entity's initial state:

Initially, an entity has no state. To set an entity's state, use one of the entity's callback functions (not to be confused with an entity state's callback function) to call its GotoState() method, shown in the following example. Once the entity state is set, the entity resides in that state and events will also be directed to that state.

Copy
function AdvancedDoor:OnReset() self:GotoState("Opened"); end

To change an entity's state:

Transitioning from the current state to any other state can also be done using the GotoState() method, as follows.

Copy
function AdvancedDoor.Server:OnHit(hit) ... if(self:IsDead())then self:GotoState("Destroyed"); end end

To query an entity's state:

Querying the state the entity is currently in can be done using the GetState() method, as follows.

Copy
if (self:GetState()=="Opened") then ... if (self:GetState()~="Opened") then ...