Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to fix "attempt to index nil with 'WaitForChild' "?

Asked by 4 years ago

My script is:

script.Parent.MouseButton1Click:Connect(function()
    local RS = game:GetService("ReplicatedStorage")
    local item = RS:WaitForChild("Sword")
    local price = 100
    local Players = game:GetService("Players")
    local player = Players.LocalPlayer
    local stats = player:WaitForChild("leaderstats")

    if stats.Money.value >= price then
        stats.Money.value = stats.Money.value - price
        local cloned = item:Clone()
        local cloned2 = item:Clone()
        cloned2.Parent = player.Backpack
        cloned.Parent = player.StarterGear
    end
end)

the whole error says:

Players.HamsterxDD.PlayerGui.ScreenGui.Frame.TextButton.Script:7: attempt to index nil with 'WaitForChild'

If anyone has a simple solution please tell me about it. I'm a beginner and i'm still practicing, any help will be appreciated.

2
Is it a local script? PixelRankYT 20 — 4y
0
If you're using a normal script (not LocalScript,) it won't be accessible. Use a LocalScript. Y_VRN 246 — 4y
0
when it's a localscript it only works on your screen. I'll find a different solution. HamsterxDD 5 — 4y

1 answer

Log in to vote
-1
Answered by 4 years ago
Edited 4 years ago
script.Parent.MouseButton1Click:Connect(function(player) --You forgot to write that there, so "player" was nil.
    local RS = game:GetService("ReplicatedStorage")
    local item = RS:WaitForChild("Sword")
    local price = 100
    local Players = game:GetService("Players")
    local stats = player.leaderstats -- We don't need "WaitForChild" there because when they click it, everything is loaded.

    if stats.Money.value >= price then
        stats.Money.value = stats.Money.value - price
        local cloned = item:Clone()
        local cloned2 = item:Clone()
        cloned2.Parent = player.Backpack
        cloned.Parent = player.StarterGear
    end
end)

Hope this helped!

0
now it's "Players.HamsterxDD.PlayerGui.ScreenGui.Frame.Sword.Script:6: attempt to index nil with 'leaderstats' " but your tips are really useful, thanks. HamsterxDD 5 — 4y
0
then add the waitforchild ViviTheLuaKing 103 — 4y
Ad

Answer this question