PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

OnClientEvent

The OnClientEvent event fires listening functions in LocalScript when either RemoteEvent/FireClient or RemoteEvent/FireAllClients is fired by the server from a Script.

This is used to retrieve remote events fired by the server and intended for the client. This event is in place to provide a method for communicating between the server and client, which is well documented in this article. This event retrieves remote events fired by the server to the client.

To fire from the client to the server, you should use RemoteEvent/FireServer and RemoteEvent/OnServerEvent.

Parameters

Name Type Default Description

The arguments passed to these methods.


Code Samples


RemoteEvents: Server to a Single Client

The server can send messages to the client through remote events in two ways: it can send a message to an individual client or it can send a message to every client at the same time.

In order to send a message to a single client, the FireClient function should be called from the server via a Script.

To listen for the message on the client, a LocalScript needs to connect a function to the OnClientEvent event of the RemoteEvent.

-- Script

local Players = game:GetService("Players")
 
local welcomePlayerEvent = Instance.new("RemoteEvent")
welcomePlayerEvent.Parent = game.ReplicatedStorage
welcomePlayerEvent.Name = "WelcomePlayerEvent"
 
local function onPlayerAdded(player)
	welcomePlayerEvent:FireClient(player)
end
 
Players.PlayerAdded:Connect(onPlayerAdded)


-- ========================================


--LocalScript 

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
 
local player = Players.LocalPlayer
local welcomePlayerEvent = ReplicatedStorage:WaitForChild("WelcomePlayerEvent")
local playerGui = player:WaitForChild("PlayerGui")
 
local welcomeScreen = Instance.new("ScreenGui")
welcomeScreen.Parent = playerGui
local welcomeMessage = Instance.new("TextLabel")
welcomeMessage.Size = UDim2.new(0, 200, 0, 50)
welcomeMessage.Parent = welcomeScreen
welcomeMessage.Visible = false
welcomeMessage.Text = "Welcome to the game!"
 
local function onWelcomePlayerFired()
	welcomeMessage.Visible = true
	wait(3)
	welcomeMessage.Visible = false
end
 
welcomePlayerEvent.OnClientEvent:Connect(onWelcomePlayerFired)