I am trying to make a script that lets me get 1 strength every time a player touches it however it's giving me the following error Workspace.dumbell.Script:5: attempt to index nil with 'leaderstats'
Here is my script: script.Parent.Touched:Connect(function(hit) local player = hit.Parent:FindFirstChild("Humanoid") local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if plr.leaderstats.Strength.Value >= 0 then wait() script.Disabled = true script.Parent.Transparency = 1 script.Parent.CanCollide = false plr.leaderstats.Strength.Value = plr.leaderstats.Strength.Value + 1 wait(1) script.Parent.Transparency = 0 script.Parent.CanCollide = true script.Disabled = false
end end)
And here is how I got leaderstats and strength:
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder") leaderstats.Name = "leaderstats" leaderstats.Parent = player local strength = Instance.new("NumberValue") strength.Name = "Strength" strength.Parent = leaderstats
This is a concurrency issue. You have 1 script making your leaderstats and another one doing the rest of the code. However you have no control over the order of which scripts run in.
Your best bet is to make sure in your script where the error is thrown to wait until the leaderstats have been made.
local player = hit.Parent:FindFirstChild("Humanoid") local plr = game.Players:GetPlayerFromCharacter(hit.Parent) -- Start here if not plr then return end -- note that GetPlayerFromCharacter can return nil if the hit.Parent is not a character. local leaderstats = plr:WaitForChild("leaderstats")
Try using IntValue instead of NumberValue.
local leaderstats = Instance.new("Folder") leaderstats.Name = "leaderstats" leaderstats.Parent = player local strength = Instance.new("IntValue") strength.Name = "Strength" strength.Parent = leaderstats