Hello. Usually whenever I use this part of the code, it’ll never give out of an error. But it’s been giving errors and I’m unsure why it is doing this.
local plr = game.Players.LocalPlayer local Char = plr.Character local Torso = Char:WaitForChild("HumanoidRootPart")
This is the error it’s giving
How would I fix this? It normally works, but this week it’s not working at all. I don’t get it, I haven’t changed anything at all.
WaitForChild
Cannot find whatever your waiting for, its returning it as “nil”.
So you should check again if the part is being spawned or exist already in the workspace.
You are referencing the player character before it has loaded in the game. Simply use this code in a LocalScript.
local plr = game.Players.LocalPlayer
repeat task.wait() until game.Workspace:FindFirstChild(plr.Name)
local char = plr.Character
local hrp = char:WaitForChild("HumanoidRootPart")
You’re kind of right, but what is actually going on is that the Character
property is nil
, so :WaitForChild()
can’t be used as it’s a function of instance
.
@aspacrer_1 repeat task.wait() untill Player.Character ~= nil
would be the best way to wait for character. (Basically what @Citrozi said but with a few improvements.)
As said above, Character
property is nil
until the player spawns. So you must wait for it.
Related links:
Nil Values (roblox.com)
Player.Character (roblox.com)
Instance:WaitForChild (roblox.com)
it does. but it appears the solution seems to be putting the local script inside of startercharacterscripts. I want it to be in a tool instead.
Ok i’ll try it out, and see if it works. If it does work i’ll let you know
Actually the best way to wait for the character is
local character = player.Character or player.CharacterAdded:Wait()
Just because it prioritizes event based programming and never yields unless it needs to. Either is fine though and it won’t make enough of a difference to care.
Do you know if one takes up more memory or data from the player? I want to know which one can reduce lag more.
Ok. So apparently all of these work. So thank you so much for the help!
The only difference is that my solution will always wait at least once. Their solution only yields if the character isn’t nil. So, I would assume his solution is faster, but it would be a very small difference.
Indeed there is no real difference here. Event driven programming is sometimes looked upon as being programmatically cleaner or more proper, but in the specific wait-for-character scenario it’s not worth splitting hairs over.
Also if you wanted to use a loop but not wait unless it’s necessary, you could use a while loop
while not player.Character do task.wait() end
For local/server scripts inside the ‘StarterCharacterScripts’ container the character can be referenced via ‘script.Parent’.
A better practice would be plr.CharacterAdded:Wait()