Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How would I make the script restart if the player died?

Hi Ive been trying to figure out something but it wont just pop in my head, Im trying to make a script so if the player dies then the script will restart all over. heres the code, any help?

randplayer = math.random(1,#players) playerchosen = players[randplayer] h.Text = "The name of the player is" ..playerchosen.Name wait(1) playerchosen.Character.Torso.CFrame = CFrame.new(Vector3.new(43.088, 26.76, -333.25))

2 answers

You should probably just make that all a function that occurs on death. Like this:

playerchosen.Character.Humanoid.Died:connect(function() --Stuff you said end)

The code cheez55 mentioned will cause the game to break if the player disconnects instead of dying. I recommend you try something like this instead:

randplayer = math.random(1,#players)
playerchosen = players[randplayer]
h.Text = "The name of the player is" ..playerchosen.Name
wait(1)
playerchosen.Character.Torso.CFrame = CFrame.new(Vector3.new(43.088, 26.76, -333.25))
-- Here's the part I added:
function RestartScript()
    script:Clone().Parent = Game.ServerScriptService -- clone the script so it restarts
    script:Destroy() -- disconnect all events in this one so it doesn't do unexpected things
end
playerchosen.Character.Humanoid.Died:connect(RestartScript) -- if the player dies
playerchosen.AncestryChanged:connect(RestartScript) -- if the player disappears from the game

This discussion is preserved as it was. New answers, comments, and votes are closed.