Hook

The Hook API allow you to listen to game events and modify the behavior/logic of the game.

Functions

Hook.Add(eventName, hookName, func)

Adds a hook.

Parameters

  • func function

    callback

Example Usage

Hook.Add("characterDeath", "characterDeathExample", function(character)
   print(character)
end)

Hook.Call(eventName, parameters)

Calls a hook.

Parameters

  • parameters table

    parameters to be passed in

Example Usage

Hook.Add("think", "happyDebuggingSuckers", function()
     Hook.Call("character.death", {}) -- ruin someone's day
end)

Hook.HookMethod(className, methodName, callback)

Deprecated

This API is deprecated and shouldn't be used anymore.

Use Hook.Patch instead.

Patches a method, the callback is called with an instance variable and a ptable variable, ptable contains dictionary of parameter name -> parameter

Parameters

  • callback function

Example Usage

Hook.HookMethod("Barotrauma.CharacterInfo", "IncreaseSkillLevel", function (instance, ptable)
   print(string.format("%s gained % xp", instance.Character.Name, ptable.increase))
end, Hook.HookMethodType.After)

Hook.Patch(identifier, className, methodName, parameterTypes, callback, hookType)

Attaches a prefix/postfix to a method. Used for modifying the behavior of methods.

Parameters

  • identifier string optional

    a string that identifies this patch (unique per patched method)

  • className string

    the fully-qualified name of the type to patch

  • methodName string

    the name of the method to patch

  • parameterTypes {string} optional

    the type of the parameters -- used for disambiguating between overloads

  • callback function

    function that is called before/after the patched method executes (see hookType parameter)

Returns

  • string

    returns the identifier. If no identifier is supplied, a randomly generated one is returned instead.

Example Usage

-- Postfix example: do some logging whenever CharacterInfo.IncreaseSkillLevel is called
Hook.Patch("Barotrauma.CharacterInfo", "IncreaseSkillLevel", function(instance, ptable)
  print(string.format("%s gained % xp", instance.Character.Name, ptable["increase"]))
end, Hook.HookMethodType.After)

-- More advanced example
Hook.Patch(
  "Barotrauma.Character",
  "CanInteractWith",
  {
    "Barotrauma.Item",
     -- ref/out parameters are supported
     "out System.Single",
     "System.Boolean"
  },
  function(instance, ptable)
    -- This prevents the original method from executing, so we're
    -- effectively replacing the method entirely.
    ptable.PreventExecution = true
    -- Modify the `out System.Single` parameter
    ptable["distanceToItem"] = Single(50)
    -- This changes the return value to "null"
    return nil
  end, Hook.HookMethodType.Before)

See Also

Hook.Remove(eventName, hookName)

Removes a hook.

Parameters

Example Usage

Hook.Remove("character.death", "characterDeathExample")

Hook.RemovePatch(identifier, className, methodName, parameterTypes, hookType)

Removes a patch from a method.

Parameters

  • identifier string

    the identifier of the patch to remove

  • className string

    the fully-qualified name of the type to unpatch

  • methodName string

    the name of the method to unpatch

  • parameterTypes {string} optional

    the type of the parameters -- used for disambiguating between overloads

  • hookType Hook.HookMethodType

    the patch type

Returns

  • boolean

    returns true if patch was successfully removed, otherwise false

Example Usage

-- Unpatch a method using a known identifier
Hook.Patch("mySuperCoolPatch", "Barotrauma.Character", "IsInteractable", function(instance, ptable)
  -- ...
end, Hook.HookMethodType.After)
local success = Hook.RemovePatch("mySuperCoolPatch", "Barotrauma.Character", "IsInteractable", Hook.HookMethodType.After)

-- Unpatch a method using a randomly generated identifier
local patchId = Hook.Patch("Barotrauma.Character", "IsInteractable", function(instance, ptable)
  -- ...
end, Hook.HookMethodType.After)
local success = Hook.RemovePatch(patchId, "Barotrauma.Character", "IsInteractable", Hook.HookMethodType.After)

Tables

ParameterTable

A table of the parameters that a C# method was called with.

This is used in the Hook.Patch callback.

In order to access or modify parameters, you have to use the array accessor syntax, e.g. ptable["myParam"]

Fields

  • PreventExecution

    if set to true, the original method and remaining postfix/prefixes will be skipped

  • ReturnValue

    the return value of the C# method

  • OriginalParameters read-only

    the parameters passed to the C# method, before any modifications by the patch(es)

  • OriginalReturnValue read-only

    the return value of the C# method, before any modifications by the patch(es)

Hooks

Hooks are functions that get called when events happen in-game, e.g. chat messages.

These can be used with Hook.Add and Hook.Call.

afflictionUpdate(affliction, characterHealth, limb)

Gets called every time an affliction updates.

Parameters

  • affliction

  • characterHealth

  • limb

canUseVoiceRadio(sender, receiver)

Check if a client is allowed to hear radio voice to another client, return true to allow, false to disallow.

Parameters

  • sender

  • receiver

changeFallDamage()

Incomplete

Documentation for this section is incomplete and needs expanding.

changeLocalVoiceRange(sender, receiver)

Changes the local voice range, return a number to change the local voice range, 1 = normal, 0.5 = lower range, 2 = higher range.

Parameters

  • sender

  • receiver

character.applyAffliction(character, limbHealth, newAffliction, allowStacking)

Gets called every time an affliction is applied to a character.

Parameters

  • character

  • limbHealth

  • newAffliction

  • allowStacking

character.applyDamage(characterHealth, attackResult, hitLimb, allowStacking)

Gets gets called every time a character gets damaged by an attack.

Parameters

  • characterHealth

  • attackResult

  • hitLimb

  • allowStacking

character.created(createdCharacter)

Gets called everytime a character is created.

Parameters

  • createdCharacter character

character.damageLimb(character, worldPosition, hitLimb, afflictions, stun, playSound, attackImpulse, attacker, damageMultiplier, allowStacking, penetration, shouldImplode)

Gets gets called every time a limb gets damaged by an attack.

Parameters

  • character

  • worldPosition

  • hitLimb

  • afflictions

  • stun

  • playSound

  • attackImpulse

  • attacker

  • damageMultiplier

  • allowStacking

  • penetration

  • shouldImplode

character.death(character)

Gets called everytime a Character dies.

Parameters

  • character Character

    A dead Character.

Example Usage

Hook.Add("character.death", "characterDeathExample", function(character)
   print(character)
end)

character.giveJobItems(character, waypoint)

Gets called after the character is given the job items, useful if your script only wants to check for newly created characters in campaign gamemode.

Parameters

  • character character

  • waypoint WayPoint

chatMessage(message, sender)

Gets called everytime someone sends a chat message, return true to cancel message

Parameters

  • sender client

client.connected(connectedClient)

Called when a client connects

Parameters

  • connectedClient client

client.disconnected(disconnectedClient)

Called when a client disconnects

Parameters

  • disconnectedClient client

gapOxygenUpdate(gap, hull1, hull2)

Gets called every update when a gap passes oxygen

Parameters

  • gap

  • hull1

  • hull2

human.CPRFailed(animController)

Called after the CPR skill check fails.

Parameters

  • animController

human.CPRSuccess(animController)

Called after the CPR skill check succeeds.

Parameters

  • animController

husk.clientControl(client, husk)

Incomplete

Documentation for this section is incomplete and needs expanding.

Parameters

  • client

  • husk

inventoryItemSwap(inventory, item, characterUser, index, swapWholeStackBool)

Gets called every time items are swapped, return true to cancel

Parameters

  • inventory

  • item

  • characterUser

  • index

  • swapWholeStackBool

inventoryPutItem(inventory, item, characterUser, index, removeItemBool)

Gets called every time an item is moved from one inventory slot to another, return true to cancel

Parameters

  • inventory

  • item

  • characterUser

  • index

  • removeItemBool

item.applyTreatment(item, usingCharacter, targetCharacter, limb)

Gets called whenever an item is used as a treatment (eg. bandages).

Parameters

  • item

  • usingCharacter

  • targetCharacter

  • limb

item.combine(item, deconstructor, characterUser, allowRemove)

Gets called every time two items are combined, eg: drag an half empty magazine to another half empty magazine to combine

Parameters

  • item

  • deconstructor

  • characterUser

  • allowRemove

item.created(item)

Gets called every time an item is created.

Parameters

  • item

item.deconstructed(item, otherItem, userCharacter)

Gets called every time an item is deconstructed. Return true to prevent item from being removed.

Parameters

  • item

  • otherItem

  • userCharacter

item.drop(item, character)

Gets called whenever an item is dropped, You can return true to cancel.

Parameters

  • item

  • character

item.equip(item, character)

Gets called whenever an item is equipped. Return true to cancel.

Parameters

  • item

  • character

item.interact(item, characterPicker, ignoreRequiredItemsBool, forceSelectKeyBool, forceActionKeyBool)

Gets called every time an item is interacted, eg: picking item on ground, fixing something with wrench

Parameters

  • item

  • characterPicker

  • ignoreRequiredItemsBool

  • forceSelectKeyBool

  • forceActionKeyBool

item.readPropertyChange(item, property, parentObject, allowEditing, client)

Incomplete

Documentation for this section is incomplete and needs expanding.

Parameters

  • item

  • property

  • parentObject

  • allowEditing

  • client

item.removed(item)

Gets called every time an item is removed.

Parameters

  • item

item.secondaryUse(item, itemUser)

Same as itemUse.

Parameters

  • item

  • itemUser

item.unequip(item, character)

Same as itemEquip, but for unequipping.

Parameters

  • item

  • character

item.use(item, itemUser, targetLimb)

Gets called every time an Item gets "Used".

Parameters

  • item

  • itemUser

  • targetLimb

jobsAssigned()

Called each time a new round start job has been assigned, this context allows for you to change the role before it's applied in game.

Example Usage

Hook.Add("jobsAssigned", "", function ()
  for key, value in pairs(Client.ClientList) do
    value.AssignedJob = JobVariant(JobPrefab.Get("assistant"), 0)
  end
end)

keyUpdate()

Incomplete

Documentation for this section is incomplete and needs expanding.

loaded()

Called after all mods are executed.

meleeWeapon.handleImpact(meleeComponent, targetBody)

Called when a melee weapon has impacted a physical object.

Parameters

  • meleeComponent

  • targetBody

modifyChatMessage(chatMessage, wifiComponentSender)

Called right before a message is going to be sent, return true to stop message from being sent.

Parameters

  • chatMessage

  • wifiComponentSender

netMessageReceived(netMessage, header, client)

Called after a net message is received

Parameters

  • netMessage

  • header

  • client

roundEnd()

Called on round end

roundStart()

Called on round start

serverLog(text, serverLogMessageType)

Gets called everytime something is logged to the Server Log, do not call print() inside this function, i repeat, do not call print() inside this function.

Parameters

  • text

  • serverLogMessageType

signalReceived(signal, connection)

Gets called everytime an Item receives a wire signal

Parameters

  • signal

  • connection

signalReceived.YourItemIdentifier(signal, connection)

Gets called everytime the specified item receives a signal.

Parameters

  • signal

  • connection

statusEffect.apply.YourItemIdentifier(statusEffect, deltaTime, item, targets, worldPosition)

Called when a status effect is applied to the specified item, useful for things like medical items. You can also return true to cancel out the status effect.

Parameters

  • statusEffect

  • deltaTime

  • item

  • targets

  • worldPosition

Example Usage

 Hook.Add("statusEffect.apply.antibleeding1", "test", function (effect, deltaTime, item, targets, worldPosition)
    if effect.type == ActionType.OnUse then
        print(effect, ' ', item, ' ', targets[3])
        return true
    end
end)

stop()

Called when the script execution is terminating.

think()

Game's fixed update rate, gets called normally 60 times a second.

traitor.findTraitorCandidate(character, team)

Return true to accept traitor candidate.

Parameters

  • character

  • team

traitor.traitorAssigned(traitor)

Incomplete

Documentation for this section is incomplete and needs expanding.

Parameters

  • traitor

tryChangeClientName(client, newName, newJob, newTeam)

Called when a client tries to change his name, return false to prevent the name from being changed.

Parameters

  • client

  • newName

  • newJob

  • newTeam

wifiSignalTransmitted(wifiComponent, signal, sentFromChat)

Gets called everytime a WifiComponent starts transmitting a signal

Parameters

  • wifiComponent

  • signal

  • sentFromChat