How to use OnServerEvent for a single player?

Hey! I’m trying to make a script that fires remote events. With those remote events your character will be set to AFK and a billboard gui with “AFK” will appear above your head.

Everything works, except the gui appears for everyone, which I kind of expected, but just don’t know how to fix it.

Script:

game.Players.PlayerAdded:Connect(function(player)
	wait(6)
	local gui = game.ReplicatedStorage.AfkGui:Clone()
	local label = gui.Label
	
	gui.Parent = player.Character.Head
	
	label.Text = ""
	game.ReplicatedStorage.Events.AfkFired.OnServerEvent:Connect(function()
		player.Afk.Value = true
		label.Text = "AFK"
	end)
	
	game.ReplicatedStorage.Events.AfkDisabled.OnServerEvent:Connect(function()
		player.Afk.Value = false
		label.Text = ""
	end)
end)

You can make a function specifcly for the afk tagging outside the PlayerAdded function because the first argument passed by a RemoteEvent is the player who fired the event : RemoteEvent | Roblox Creator Documentation

The OnServerEvent signal returns an argument which is the player that called FireServer on the remote

game.ReplicatedStorage.Events.AfkFired.OnServerEvent:Connect(function(plr)
plr.Afk.Value=true
plr.Character.Head.AfkGui.Label.Text="AFK"
end)

You should also place it outside of the PlayerAdded event

1 Like

Why?
And if I place it outside, how will I put the gui in the player characters head? (best place imo)

the OnServerEvent, not the other code

1 Like

Put these inside a different script or not inside the game.Players.PlayerAdded function or whatever:

game.ReplicatedStorage.Events.AfkFired.OnServerEvent:Connect(function(player)
		player.Afk.Value = true
		label.Text = "AFK"
	end)
game.ReplicatedStorage.Events.AfkDisabled.OnServerEvent:Connect(function(player)
		player.Afk.Value = false
		label.Text = ""
	end)

So technically when someone fires the remote event, the thing gets the player instance who fired the event, the you use it to get the BoolValue.

Clearing the code out:

game.Players.PlayerAdded:Connect(function(player)
	player:CharacterAppearanceLoaded:Wait()
	local gui = game.ReplicatedStorage.AfkGui:Clone()
	local label = gui.Label
	
	gui.Parent = player.Character.Head
	
	label.Text = ""
end)

game.ReplicatedStorage.Events.AfkFired.OnServerEvent:Connect(function(player)
		player.Afk.Value = true
		player.Character:WaitForChild("Head").AfkGui.Label.Text = "AFK"
	end)

game.ReplicatedStorage.Events.AfkDisabled.OnServerEvent:Connect(function(player)
		player.Afk.Value = false
		player.Character:WaitForChild("Head").AfkGui.Label.Text = ""
	end)

Sorry for bad grammar. Hope this helps

how do i get the value of self variable in a RemoteEvent handler then?