Walkspeed counter

A couple of issues I’d like to raise with your repro.

  1. PlayerScripts has superseded placing scripts directly in StarterGui. Handling conditions for new characters is up to the developer.

  2. Do yourself and your potential collaborators a favour, teach yourself to use GetService to fetch a service and hold it in a variable.

  3. You don’t account for an uninitialised character. If your code runs before a character is present, it will throw an error as your code assumes a truthy return for the WaitForChild statement. You can prevent this by yielding the thread until the required signal is fired and presents your needed item.

  4. A while loop has a conditional argument. Returning end if a condition isn’t met isn’t the proper way to terminate a loop, it’d be break. Return does exit out of the loop’s scope but break is the proper operator. In addition, you can just use the conditional part properly1.

1:

local Players = game:GetService("Players")

local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local characterRoot = character:WaitForChild("Humanoid")

while characterRoot do
    print(characterRoot.Velocity.Magnitude)
    wait()
end

Now obviously I have no clue if the code itself in concept works, that’s up for a test to reveal. Not as in my specific code, this whole printing of the character’s velocity.

1 Like

idk @Regen_erate code works fine for me

First @colbert2677 Is using GetService

Second, he is waiting for the character

That line of code means if the character isn’t loaded then let’s wait for it.

Sometimes this code

local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer
local Character = LocalPlayer.Character
local Humanoid = Character:WaitForChild("Humanoid")

May throw errors such as

13:58:49.834 - Players.DevOfLua.PlayerScripts.LocalScript:4: attempt to index a nil value
13:58:49.835 - Stack Begin
13:58:49.836 - Script 'Players.DevOfLua.PlayerScripts.LocalScript', Line 4
13:58:49.836 - Stack End

This is because the character wasn’t loaded yet.

1 Like

Thanks, I do use :GetService() all the time to store it in a variable, I made a rhythm game and I had to do that a lot. And yeah, I did think about that if the code ran before the player actually existed it would error. I am already aware of all of this, except for the “break” operator lol I literally thought nothing of it; I just modified (I think) @TheAviator01’s code.

BTW, it threw an error if I placed the LocalScript in StarterPlayerService. Idk why.