尝试使用 'leaderstats' 访问空值

基本上我想制作一个塔防游戏,我添加了一个按钮,点击按钮可以生成带有 AI 的塔/机器人。(脚本是本地的) 它总是用 尝试使用 'leaderstats' 访问空值 报错。(我知道这意味着游戏不知道什么是 leaderstats),我制作了一个脚本,在玩家内创建了一个名为 leaderstats 的文件夹,里面有硬币和其他东西,但它仍然不知道有一个 leaderstats 文件夹。我还尝试了 FindFirstChild(),但它只是报 尝试使用 '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 = "太贵了"
            wait(0.5)
            button.Text = "守卫 [250$]"
                button.BackgroundColor3 = Color3.new(0.603922, 0.603922, 0.603922)

            end
        end
    end)

原文链接 https://stackoverflow.com/questions/70135924

点赞
stackoverflow用户2860267
stackoverflow用户2860267

GuiButton 的 MouseButton1 事件 没有提供任何参数,因此你的 player 变量最终变成了 nil。当你尝试使用 player.leaderstats 时,它会抛出错误,因为 player 没有任何子级或属性可索引,因为它是 nil。

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

local button = script.Parent
button.MouseButton1Click:Connect( function()
    local player = game.Players.LocalPlayer
2021-11-27 18:19:35