Reputation: 1
I'm making a button increase leaderstat value of "Speed", then, apply that leaderstat value on to the WalkSpeed value of the players humanoid. (make them the same)
Here's the thing. I've done that part. The problem is, I need it to stay when the player dies and respawns, Also, my code seems to have broken for joining the game as well.
Code for joining game, In ServerScriptService:
local plrs = game:GetService("Players")
plrs.PlayerAdded:Connect(function(plr)
task.wait(3)
local humanoid = if plr.Character then plr.Character:FindFirstChild("Humanoid") else nil
if humanoid then
print("Found Humanoid")
plr:FindFirstChild("Humanoid").WalkSpeed = plr.leaderstats.Speed.value
end
end)
Here is the error: ServerScriptService.Script:10: attempt to index nil with 'WalkSpeed'
I know the issue is the fact that it isnt finding the leaderstat value, but I don't know how to fix it. Also, I need a way for this to stay after death and respawn. It is essential for my gameplay. I think the best way to do this is to just find when the player/character respawns, then apply the leaderstat value as the WalkSpeed value on the player. I just don't know where to start after this first part of joining the game.
Upvotes: 0
Views: 66
Reputation: 465
you should consider using the CharacterAdded
event inside the player object.
also value
should be Value
when indexing the IntValue.
local Players = game:GetService("Players")
Players.PlayedAdded:Connect(function(Player)
Player.CharacterAdded:Connect(function(Character) -- fires when player spawned
local Humanoid = Character:WaitForChild("Humanoid") -- wait for it to be added to the character
if not Player.leaderstats or not Player.leaderstats.Speed then return end -- leaderstats or Speed value not found?
Humanoid.WalkSpeed = Player.leaderstats.Speed.Value
end)
end)
Upvotes: 0
Reputation: 625
You aren't referencing Humanoid properly when you are trying to get the WalkSpeed. You are using plr:FindFirstChild("Humanoid")
when you should be using plr.Character:FindFirstChild("Humanoid")
or the humanoid
variable you already have. Currently, you are trying to find Humanoid in Player but it will cause attempt to index nil with 'WalkSpeed'
since Humanoid isn't in Player but Player.Character so it fails to find WalkSpeed and Humanoid.
Below I corrected the script to use the humanoid
variable when trying to get the Player's WalkSpeed.
local plrs = game:GetService("Players")
plrs.PlayerAdded:Connect(function(plr)
task.wait(3)
local humanoid = if plr.Character then plr.Character:FindFirstChild("Humanoid") else nil
if humanoid then
print("Found Humanoid")
humanoid.WalkSpeed = plr.leaderstats.Speed.value
end
end)`
Upvotes: 0