Guide me scripting a sprinting script with energy

No. Im not asking you guys to write a script for me. Im just asking for a guidance on how one would achieve something like this. Im not really good at constructing script especially when things get complex. So far i’ve already made this.

The script
    local WorkspacePlayer = game:GetService("Players).LocalPlayer.CharacterAdded:Wait()
    local UIS = game:GetService("UserInputService")
    local Energy = 60

local function SetSpeed(Speed)
	local human = WorkspacePlayer:FindFirstChild("Humanoid")
	if human then
		human.WalkSpeed = Speed
	end
end

local Run = coroutine.create(function() -- Exhaust energy while running
	while true do
		wait(1)
		Energy = Energy - 1
	end
end)

local StopRun = coroutine.wrap(function() -- Regenerate energy
	coroutine.yield(Run)
	SetSpeed(16)
	wait(1)
	while Energy < 60 do
		Energy = Energy + 1
		wait(0.25)
	end
	coroutine.yield()
end)

local CheckEnergy = coroutine.wrap(function() -- When energy deplete
	while true do
		if Energy == 0 then
			coroutine.resume(StopRun)
		end
	end
end)

UIS.InputBegan:Connect(function(Key,Bool)
	if Bool then return end
	if Key == Enum.KeyCode.LeftShift then
		SetSpeed(25)
		coroutine.resume(Run)
		CheckEnergy()
	end
end)

UIS.InputEnded:Connect(function(Key,Bool)
	if Bool then return end
	if Key == Enum.KeyCode.LeftShift then
		coroutine.resume(StopRun)
	end
end)

of course this script doesn’t work. As this is made in few go, and im already run out of idea on how to do this efficiently. Any criticsm on what should i do to make it work would really help me alot. I need some guidance on how people do this. I’ve only thinked to use coroutine but im really new at it so give me some tips about coroutine.

Yea this post is a little bit weird

local WorkspacePlayer = workspace:WaitForChild(game:GetService(“Players”).LocalPlayer.Name)

I looked at the first line and got really confused. I’m not fully understanding what you are trying to get… I don’t understand why you are looking for the “Players” service inside of workspace.

He’s doing a very wrong and round about form of

local character = game:GetService("Players").LocalPlayer.CharacterAdded:Wait();
2 Likes

Ah. Thats basicall this

local PlayerName = game:GetService("Players").LocalPlayer.Name

local WorkspacePlayer = workspace:WaitForChild(PlayerName)

It find the player model in workspace using the player name on players service so i can access its humanoid… Idk if i explained it well.

Ah yeah i should fix it

Did you mean CharacterAdded?

local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()

@FatFitFut please use this instead

4 Likes

Yes I did mean that. I was thinking that in my head and thought I typed that but typed it wrong. Thank you for correcting me!

Sure. I never knew that existed. Always used that kind of form everytime i access my character. Thanks