User Tools

Site Tools


events

Events

Some core types use events. These events can be used to run a function when a certain trigger happens on a specific object.

Triggering events

To trigger an event on an object, call this event from the chosen object. Events are designed to be triggered by their owner, and listened to by other objects.

For example, if you create a new component type extending COMP_WORKPLACE, you can do the following in one of this type's function:

myCustomWorkplace.registerVillager = function(villager)
    ...
    self.ON_ASSIGNED_WORKER_CHANGED(villager)
    ...
end

Registering to events

When you create a custom type, objects of this type can listen to event triggers, and run functions when those events are triggered. For this, you use three new event-specific functions in the event table.

register

Register to an event triggered on a specific target object.

void event.register(target, objectEvent, callback)

Name Type Description
target userdata the target custom-type object
objectEvent event
callback function Must have the same parameters as the event
local compMainGameLoop = getLevel():find("COMP_MAIN_GAME_LOOP")
event.register(self, compMainGameLoop.ON_NEW_DAY, function()
	myMod:log("New day!")
end)
 
local parentBuilding = getOwner():findFirstObjectWithComponentUp("COMP_BUILDING")
event.register(self, parentBuilding.ON_CUSTOM_NAME_CHANGED, function(newName)
	myMod:log("Building name changed to " .. newName)
end)

unregister

Stops listening to an event registered on a specific target object.

void event.unregister(target, objectEvent)

Name Type Description
target userdata the target custom-type object
objectEvent event
local compMainGameLoop = getLevel():find("COMP_MAIN_GAME_LOOP")
event.unregister(self, compMainGameLoop.ON_NEW_DAY)

clear

Stops listening to all events registered on the target object

void event.clear(target)

Name Type Description
target userdata the target custom-type object
events.txt · Last modified: 2020/05/22 12:23 by maxime

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki