Search code examples
luaroblox

Attempt to index nil with 'leaderstats'


So basicially i wanted to make a tower defense game, I added a button which on click spawn in towers / robots with AI. (the script is local) It always errors me with Attempt to index nil with 'leaderstats'. (I know that this means the game doesnt know what leaderstats is), I made a script that makes the folder called leaderstats inside of the player with the coins and stuff inside but it still doesnt know that theres a leaderstats folder. I also tried out FindFirstChild() but it just said Attempt to index nil with 'FindFirstChild'. Can anyone help me?

local button = script.Parent

button.MouseButton1Click:Connect(function(player)
        local spawner = game.Workspace.ts1
    local money = player.leaderstats.Cash.Value
        if money >= 250 then
            money = money - 250
            local clone = game.ReplicatedStorage.Allies.Guard:Clone()
            clone.Parent = workspace
            clone.HumanoidRootPart.CFrame = spawner.HumanoidRootPart.CFrame
        else
            if money <= 250 then
            button.BackgroundColor3 = Color3.new(1, 0, 0)
            button.Text = "Too Expensive"
            wait(0.5)
            button.Text = "Guard [250$]"
                button.BackgroundColor3 = Color3.new(0.603922, 0.603922, 0.603922)

            end
        end
    end)


Solution

  • The MouseButton1 event on GuiButtons doesn't provide any arguments, so your player variable ends up being nil. And when you try to say player.leaderstats, it throws the error because player doesn't have any children or properties to index because it is nil.

    But since this is a LocalScript, you can easily access the Player object using the Players.LocalPlayer object.

    local button = script.Parent
    button.MouseButton1Click:Connect( function()
        local player = game.Players.LocalPlayer