This tutorial will guide you through creating a module script, which provides a function allowing registration for a particular event. We will place the module script in ServerStorage, making it available on demand without auto-replication to clients. A test script, placed in the ServerScriptService, will run at server startup, registering to the PlayerAdded event and utilizing our module script.
Our event will trigger each time a player jumps, and the function registering to this event will simply print a statement in the output.
Step 1: Creating the Module Script
- Navigate to the ServerStorage folder in your project.
- Click the plus icon on the right side of folder, from the list of possible objects select
ModuleScript
. - Rename the new module script to
JumpEventModule
.
Input the following code:
local JumpEventModule = {} function JumpEventModule.CreateJumpEventForPlayer(targetPlayer:Player) local jumpEvent = Instance.new("BindableEvent") local function onCharacterAdded(character:Instance) local playerHumanoid = character:FindFirstChildOfClass("Humanoid") if playerHumanoid ~= nil then playerHumanoid:GetPropertyChangedSignal("Jump"):Connect(function() if playerHumanoid.Jump then jumpEvent:Fire() end end) end end targetPlayer.CharacterAdded:Connect(onCharacterAdded) return jumpEvent.Event end return JumpEventModule
In this script, JumpEventModule
is a table that will hold our functions. CreateJumpEventForPlayer
is a function that creates a new BindableEvent each time a player character is added to the game. We then listen for a change in the Jump
property of the player’s humanoid. If this property changes (i.e., the player jumps), the jumpEvent
fires.
Step 2: Adding a Script to the ServerScriptService
- Navigate to the ServerScriptService in your project.
- Right-click within the folder, select
Script
, then selectScript
from the dropdown menu. This will create a new script. - Replace the contents of this script with the following code:
local PlayersService = game:GetService("Players") local ServerStorageService = game:GetService("ServerStorage") local JumpEventModule = require(ServerStorageService.JumpEventModule) local function onPlayerJoined(targetPlayer:Player) JumpEventModule.CreateJumpEventForPlayer(targetPlayer):Connect(function() print(targetPlayer.Name .. " has jumped!") end) end PlayersService.PlayerAdded:Connect(onPlayerJoined)
In this script, PlayersService
and ServerStorageService
are references to the Players and ServerStorage services. JumpEventModule
is a reference to the module script we created earlier. The onPlayerJoined
function connects to the PlayerAdded
event of the PlayersService
, listening for when a new player joins the game. Upon a player joining, it registers to the jump event we created in the module script, printing a message whenever the player jumps.
By following these steps, you’ve now created a system that detects and responds to each player’s jump action.