【问题标题】:Roblox Lua - attempt to index nil with 'stats' (leaderstats)Roblox Lua - 尝试使用“stats”(leaderstats)索引 nil
【发布时间】:2022-02-07 01:42:49
【问题描述】:

我想做这个,当 baseFinal 被一个块(Bloque)触及时,它会给你钱并且块被破坏。它给了我一个错误:尝试用'stats'索引nil

local base = script.Parent.Base

local baseFinal = script.Parent.Final

local plr = game.Players.LocalPlayer


baseFinal.Touched:Connect(function(hit)
    
    if hit.Name == "Bloque" then
        wait(0.6)
        plr.stats.Value = plr.stats.Value + 5  // here is the error
        hit:Destroy()
    end
     
end) 

【问题讨论】:

    标签: lua roblox


    【解决方案1】:

    错误告诉您plr 变量未定义或为零。

    由于此代码在脚本中运行,因此问题在于您如何访问 Player 对象。请参阅Players.LocalPlayer 的文档:

    此属性仅为 LocalScripts(以及它们所需的 ModuleScripts)定义,因为它们在客户端上运行。对于服务器(Script 对象在其上运行其代码),此属性为 nil。

    解决这个问题的方法是通过另一种方式访问​​ Player 对象。一种方法是连接到 Players.PlayerAdded 信号。

    local base = script.Parent.Base
    local baseFinal = script.Parent.Final
    
    local connections = {}
    
    game.Players.PlayerAdded:Connect( function(plr)
        -- listen for Players to touch the block
        local connection = baseFinal.Touched:Connect( function(hit)
            if hit.Name == "Bloque" then
                wait(0.6)
                plr.stats.Money.Value = plr.stats.Money.Value + 5
                hit:Destroy()
            end
        end)
    
        -- hold onto the connection to clean it up later
        connections[plr] = connection
    end)
    
    -- clean up when the Player leaves
    game.Players.PlayerRemoving:Connect( function(plr)
        connections[plr]:Disconnect()
    end)
    

    【讨论】:

    • 并将plr.stats.Value替换为plr.stats.Money.Value
    • 非常感谢,我唯一的问题是排行榜上看不到钱但最复杂的事情解决了,我可以继续前进
    • 我刚刚意识到,只要“Bloque”物体接触到底座,这段代码就会给所有玩家 5 钱。这可能不是您想要的。
    【解决方案2】:

    这很可能是因为当您尝试引用一个值时,您必须在其后面加上.Value 才能更改值本身。假设您有一个 stats 文件夹,您应该改用 plr.stats.Value.Value。 下次,请向我们展示您的对象结构,以便我们更好地了解错误是什么。谢谢。

    【讨论】:

    • 感谢您的评论。唯一的问题是我不是那个意思。错误不断发生。它一直在说: Workspace.GeneradorBloques-Tycoon1.GeneradorBloque.Base.Script:11:尝试用“stats”索引 nil 这是工作区的图片和 stats 文件夹的位置:link
    • 我能看到stats文件夹的结构吗?
    • 这里有:link
    • 问题在于您将脚本中的值引用为Value,而不是其名称Money。试试plr.stats.Money.Value = plr.stats.Money.Value + 5
    • 我是个白痴。我刚刚意识到这是在常规脚本而不是 LocalScript 中运行的。请参阅 Kylaaa 的语法答案并使用 plr.stats.Money.Value 来引用它。给您带来的不便深表歉意。
    猜你喜欢
    • 2020-12-16
    • 2020-11-22
    • 2022-01-05
    • 2022-10-13
    • 2022-01-10
    • 2022-10-24
    • 2021-09-23
    • 2021-09-30
    • 2022-11-07
    相关资源
    最近更新 更多