How do I write a script to respawn a player when they touch a part?
COMMUNITY QUESTION
How do I write a script to respawn a player when they touch a part?
2 answers
Simple!
function onTouch(part)
if game.Players.GetPlayerFromCharacter(part.Parent) then --If a player touches then
Player = game.Players:GetPlayerFromCharacter(part.Parent)
Player:LoadCharacter() --Respawn the player!
end
end
script.Parent.Touched:connect(onTouch)
First off you would want it so that it would fire off an event when something touches it
script.Parent.Touched:connect(function(part)
end)
Now you would want to check if the part that touched it was part of a player
getPlayer = function(part)
local player -- nil
for _, v in pairs(game.Players:GetChildren()) do
if part:IsDescendantOf(v.Character) then
--This will loop through the players and if it was a part of any of the characters then it will go here
player = v --The current value
end
end
return player
end
script.Parent.Touched:connect(function(part)
local player = getPlayer(part)
if player ~= nil then
end
end)
Next we will want to make it so the player will respawn and add a debounce so it doesn't glitch out!
local db = false
getPlayer = function(part)
local player
for _, v in pairs(game.Players:GetChildren()) do
if part:IsDescendantOf(v.Character) then
--This will loop through the player and if the part was a part of any of the characters then it will go here
player = v --The current value
end
end
return player
end
script.Parent.Touched:connect(function(part)
if db == true then return end --Stop running if debounce is equal to true
local player = getPlayer(part)
if player ~= nil then
db = true
player:LoadCharacter() --Respawns the character
wait(0.5) --So it doesn't run the event multiple times
db = false
end
end)
2 comments
2
All that code isn't necessary. Just use GetPlayerFromCharacter!
0
No it is due to the fact if another part of you hit it (your hat part or if you have a morph then that part) it won't find it so I'd rather be able to defend that before getting down-voted twice...
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
Do you want to kill them?