I created a simple ShiftToRun
LocalScript
(pasted below).
It works fine, but after death + respawn it stops working, if I put it in: StarterPlayerScripts, or ReplicatedFirst.
However, it keeps working after death, if I put it in StarterGui.
I have a few questions (if I may?):
LocalScript
is destroyed (and thus the callback is removed from ContextActionService
) on death for some reason. Is that about right? LocalScripts
after death? Is StarterGui
the only way to persist for a script after death?local player = game.Players.LocalPlayer local cas = game:GetService("ContextActionService") local runSpeed = script.RunSpeed.Value local isRunning = false local char = player.Character or player.CharacterAdded:wait() local humanoid = char:WaitForChild('Humanoid') local walkSpeed = humanoid.WalkSpeed local toggleRun = function(actionName, actionInputState, actionInputObject) --if actionInputState == Enum.UserInputState.Begin then isRunning = not isRunning if isRunning then humanoid.WalkSpeed = runSpeed else humanoid.WalkSpeed = walkSpeed end --end end cas:BindAction("toggleRun", toggleRun, true, Enum.KeyCode.LeftShift)
The script will persist on death as long as it is not parented to something that is destroyed on death, such as Backpack
or Character
.
Putting it into the StarterGui
doesn't make it persist on death but rather reruns the same script each time you respawn.
Now, why doesn't your script work? The answer is simple: you are caching the Humanoid.
Each time the player respawns, they have a different char and different humanoid. And in your script, you define the humanoid
variable as the current humanoid and don't update it on respawn.
So what you should do, is declare the humanoid inside the callback instead.
local player = game.Players.LocalPlayer local cas = game:GetService("ContextActionService") local runSpeed = script.RunSpeed.Value local isRunning = false local toggleRun = function(actionName, actionInputState, actionInputObject) local humanoid = player.Character and player.Character:WaitForChild("Humanoid") or player.CharacterAdded:Wait():WaitForChild("Humanoid") --if actionInputState == Enum.UserInputState.Begin then isRunning = not isRunning if isRunning then humanoid.WalkSpeed = runSpeed else humanoid.WalkSpeed = walkSpeed end --end end cas:BindAction("toggleRun", toggleRun, true, Enum.KeyCode.LeftShift)