Skip to main content

Events

Events are a type of member you can subscribe to in your ModScripts to execute code in reaction to something happening.

You create an event handler that takes 2 parameters:

  1. sender - The C# object that raised the event
  2. eventArgs - An object that sometimes contains information about the event

Subscribing to Events

To subscribe to an event, you need to first define the event handler function that runs in response to the event triggering:

registerType("HealthChangedEventArgs")
registerType("IHasHealth") -- this is an example of a YOMG2 interface
registerType("Player")
registerType("Vector3")

local healthComponent = getCurrentItem().GetComponent("IHasHealth")

function healthChangedHandler(sender, eventArgs)
local scale = healthComponent.transform.localScale
local healthDecrease = eventArgs.OldHealth - eventArgs.NewHealth
scale.x = scale.x + (0.069 * healthDecrease * Mathf.Sign(scale.x)) -- if scale is negative (coz item is facing other direction), we gotta subtract to make it wider
healthComponent.transform.localScale = scale -- make size wider every time health changes. lol.
end

healthComponent.HealthChanged.add(healthChangedHandler)
-- REMEMBER TO UNSUBSCRIBE!!!! (see below)
note

You can only subscribe to events that match the standard EventHandler pattern (which is the case for all YOMG2 code), and meet MoonSharp's event requirements

Unsubscribing from Events

It is extremely important that you unsubscribe from all events you've subscribed to. Usually, you would do this when exiting the level, which is when the cleanup function is called:

-- ...code from above
function cleanup()
healthComponent.HealthChanged.remove(healthChangedHandler)
end

...but you can do this whenever.