Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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.

3 comments

2

Is it a local script?

0

If you're using a normal script (not LocalScript,) it won't be accessible. Use a LocalScript.

0

when it's a localscript it only works on your screen. I'll find a different solution.

1 answer

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!

2 comments

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.

0

then add the waitforchild

This discussion is preserved as it was. New answers, comments, and votes are closed.