Using Lifecycle Events

Lifecycle events are mandatory for your singletons to react to certain events like the start of the singleton. You have to explicitly define the lifecycle events that are used in order to have them called by the framework. Here's an example:

local Service = {
    lifecycles = { "start" }
}

function Service:start()
    print("Hi!")
end

return Service

The function Service:start() will be called when the singleton starts for the first time.

You can also use different function names like so:

local Service = {
    lifecycles = { start = "whenStart" }
}

function Service:whenStart()
    print("Hi!")
end

return Service

In the above example, the start lifecycle is implemented and instead of the start function, whenStart will be called.

📈Available Lifecycle Events

Note

All lifecycle events are called on the singleton. This means that every lifecycle event has to be implemented as a selfcall (Service:func() instead of Service.func()). You can still define them using just a normal dot like so: function Service.func(this, ...)

Some events shouldn't yield

Here's a list of all lifecycle events, and their arguments:

Signature
Description
Called once?
Can Yield?

start()

Called once the singleton starts

Yes

onShutdown()

(server-only) Called when the game server is stopping

Yes, but will halt

onStep(dt: number)

(client-only) Called every frame (RunService.RenderStepped)

Yes, but shouldn't

onTick(dt: number)

Called every heartbeat (RunService.Heartbeat)

Yes, but shouldn't

onPhysics(dt: number)

Called after every physics simulation (RunService.PostSimulation)

Yes, but shouldn't

onPlayerJoin(player: Player)

(server-only) Called once a player joins (Players.PlayerAdded)

Yes

onPlayerLeave(player: Player)

(server-only) Called once a player leaves (Players.PlayerRemoving)

Yes

Last updated