Skip to main content

Events

Contains functions for creating custom events.

info

This module can only be used in Entity scripts.

Functions

create(condition, callback)

Defines a custom event, given a condition and a callback function that will be called whenever the condition changes from false to true.

Parameters

  • condition The conditional expression.
  • callback Function to be called when the condition resolves to true.

Returns

A string with the unique ID of the event created.

Example

Make a robot chase the last player that joined the world until it gets 3 units away for him. It will also chase him if the player is out of range (3 units in this case).

local playerJoined = nil
local robotRange = 3

function playerInRange()
local distance = Vector3.distance(playerJoined.position, self.position)
return distance <= robotRange
end

function playerOutOfRange()
local distance = Vector3.distance(playerJoined.position, self.position)
return distance > robotRange
end

function moveToPlayerJoined()
while playerOutOfRange() do
Movement.moveToPlayer(AsyncMode.Continue)
Task.yield()
end
end

function stopMoving()
Movement.stop()
end

function onStart()
playerJoined = Players.getRandomPlayer()
Events.create(playerOutOfRange, moveToPlayerJoined)
Events.create(playerInRange, stopMoving)
end

delete(eventId)

Removes a custom event.

Parameters

  • eventId The unique ID of the event to delete.

Example

Using previous example (Events.create()), we can make a NPC stop chasing the player once we interact with the NPC.

-- adding to Events.create() example

local chasingEvent = nil
function onPlayerJoin(player)
--...
chasingEvent = Events.create(playerOutOfRange, moveToPlayerJoined)
end

function onInteractStart(clientId)
Events.delete(chasingEvent)
end