尝试使用 'leaderstats' 索引 nil

Attempt to index nil with 'leaderstats'

所以基本上我想制作一款塔防游戏,我添加了一个按钮,点击它会在带有 AI 的塔/机器人中生成。 (脚本是本地的)它总是让我出错 Attempt to index nil with 'leaderstats'。 (我知道这意味着游戏不知道 leaderstats 是什么),我制作了一个脚本,在玩家内部创建了一个名为 leaderstats 的文件夹,其中包含硬币和其他东西,但它仍然不知道有一个 leaderstats 文件夹。我也试过 FindFirstChild() 但它只是说 Attempt to index nil with 'FindFirstChild'。谁能帮帮我?

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)

MouseButton1 event on GuiButtons 不提供任何参数,因此您的 player 变量最终为 nil。当您尝试说 player.leaderstats 时,它会抛出错误,因为玩家没有任何要索引的子项或属性,因为它是 nil。

但由于这是一个 LocalScript,您可以使用 Players.LocalPlayer 对象轻松访问 Player 对象。

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