humanoid:Move() stop working after reconnecting

hello! i am making thing: when player press any key - he start moving by itself in direction he’s looking at but after dying the system resets and to start moving again press any key. I tried making it with connections but after death and trying to connect connection again - humanoid:Move() stop working :frowning:

script:

local plrs = game:GetService("Players")
local runService = game:GetService("RunService")
local uis = game:GetService("UserInputService")
local replicatedStorage = game:GetService("ReplicatedStorage")

local plr = plrs.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local cam = workspace.CurrentCamera
local hum = char:WaitForChild("Humanoid")
local humRoot = char:WaitForChild("HumanoidRootPart")

local is_moving = false
local connection

local function startMovement()
	is_moving = true
	connection = runService.RenderStepped:Connect(function()
		local cam_looking_vec = cam.CFrame.LookVector
		local move_direction = Vector3.new(cam_looking_vec.X, 0, cam_looking_vec.Z).Unit
		hum:Move(move_direction, false)
	end)
end

hum.Died:Connect(function()
	if connection then
		connection:Disconnect()
		connection = nil
		is_moving = false
	end
end)

uis.InputBegan:Connect(function(key)
	if is_moving then return end
	if key.KeyCode == Enum.KeyCode.W then
		startMovement()
	elseif key.KeyCode == Enum.KeyCode.S then
		startMovement()
	elseif key.KeyCode == Enum.KeyCode.A then
		startMovement()
	elseif key.KeyCode == Enum.KeyCode.D then
		startMovement()
	end
end)

uis.InputBegan:Connect(function(key)
	if key.KeyCode == Enum.KeyCode.W then
		hum.WalkSpeed = 25
	elseif key.KeyCode == Enum.KeyCode.S then
		hum.WalkSpeed = 10
	end
end)

uis.InputEnded:Connect(function(key)
	if key.KeyCode == Enum.KeyCode.W or key.KeyCode == Enum.KeyCode.S then
		hum.WalkSpeed = 16
	end
end)

heres how localscripts on roblox work

if localscript is in starterplayerscripts the localscript will be parented to the player so even if character of player died the script will still stay the same

if localscript is in startercharacterscripts the localscript and if player died the script will run everytime the character respawns

if localscript is in replicatedfirst than script will run before player is loaded into the game

i think the issue youre experiencing is character respawning so instead of doing

Char = plr.Character you could just do

plr.Character in scripts so it automatically finds and uses the latest character player has

i would also suggest doing some printing as debugging so you have more in depth knowledge on whats going on

tysm, it works. Have a good day! <3

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.