I want to have the game do something when the player leaves the game. I've done some research and found PlayerRemoved, but I've never used the function before, and when I attemped to use it, nothing really happened at all when a player left. Could someone please help me out?
local event = game:GetService("ReplicatedStorage").terminalOff game.GetService("Players").PlayerRemoving:Connect(function(player) event:FireServer(game:GetService("Players").LocalPlayer) end)
The code is in a local script.
When a player leaves the game, an event will be fired to the Server, which will tell the server to re-enable a click detector I have in my game.
There is an event called PlayerRemoving
which is triggered exactly before the player is about to leave. So you can use it to save a user's state before he leaves as an example. I have improved this code from the wiki on API:Class/Players/PlayerRemoving:
function writeLog(player) print("LOG: ", player.Name, " has indicated that he is leaving the game!") end game.Players.PlayerRemoving:connect(writeLog) -- attach writeLog() function to the event; writeLog() will execute each time a player is about to leave.
writeLog()
is therefore set up to execute each time a player is being removed from the game, executing exactly before the player leaves the game. You can attach multiple functions, and you can have much more complex functions than the one I have indicated here.
So you must not use the PlayerRemoved
event as you have indicated, but instead, PlayerRemoving
. If the above code does not work for you, please provide more details on what you are doing and we can help you accordingly.
The event is called PlayerRemoving
not PlayerRemoved
and it's and event which occurs when a player is leaving the game. Let me show you an example.
game.Players.PlayerRemoving:connect(function(player) print(player.Name.. " left the game") end)
Also I can not show you how to use this event like in 2 words but I recommend you reading this article about this event http://wiki.roblox.com/index.php?title=API:Class/Players/PlayerRemoving
I read your script carefully and I now understand why your script is not working, here is the fixed version.
local event = game:GetService("ReplicatedStorage").terminalOff
game:GetService("Players").PlayerRemoving:Connect(function() event:FireServer() end)
You do not need to add a parameter called player after :FireServer(), seems stupid.
Just go on another script and write the parameter player there at .OnServerEvent
.
game:GetService("ReplicatedStorage").terminalOff.OnServerEvent:Connect(function(player) print(player.Name.. " left the game") end)
Just like that!
idk if you misspelled it here but it's PlayerRemoving, not PlayerRemoved
so basically the code would be:
game:GetService("Players").PlayerRemoving:Connect(function(plr) --plr is a player leaving the game print(plr.Name.." is leaving") --do stuff end)