我刚刚开始在lua-roblox中编码,我遇到了“尝试用'Value'对nil进行索引”的错误,但找不到原因

所以我刚刚开始使用Lua在roblox中编码,但我找不到为什么会遇到此错误(以下为代码)

Workspace.Script:11: attempt to index nil with 'Value'

game.Players.PlayerAdded:Connect(function(player)
    local stats = Instance.new("Folder", player)
    stats.Name = "leaderstats"
    currency = Instance.new("IntValue", stats)
    currency.Name = "oil"
    currency.Value = 100
    return 0
end)

while true do
    currency.Value = 100+10 -- 这里可能有问题
    wait(5)
end
点赞
用户459640
用户459640

PlayerAdded:Connect(function ... end) 表示你正在设置一个函数,该函数将在玩家加入游戏时稍后被调用。它不会立即运行。

紧接着,脚本会进入你的 while 循环。但是 currency 还没有被设置,所以它的值只是 nil,使得 currency.Value 无效。

而且,你将 currency 全局变量设置在玩家加入时。这意味着如果它被设置了,它将是最后一个加入的玩家的统计值,并且任何在 PlayerAdded 回调之外的代码只会更改那一个玩家的内容。

2020-04-02 21:37:33
用户13072308
用户13072308

你应该把 while true 循环放在 Players.PlayerAdded 内部,这样它才能正常工作。


顺带一提:替代使用

local stats = Instance.new("Folder", player)

你应该使用

local stats = Instance.new("Folder")
stats.Parent = player

因为这个更快。

2020-05-05 18:21:56
用户14714880
用户14714880

你正在引用一个不存在的对象。'Currency' 对象基本上是 nil,修复它,基本上将 while true 循环放入其中即可。如果你使用一个点号索引(通过点号到达对象),它会显示错误。

修正后的代码

game.Players.PlayerAdded:Connect(function(player)
    local stats = Instance.new("Folder", player)
    stats.Name = "leaderstats"
    currency = Instance.new("IntValue", stats)
    currency.Name = "oil"
    currency.Value = 100
    return 0

   while true do
    currency.Value = 100 + 10 -- 应该放在这里
    wait(5)
end

end)
2021-07-19 08:54:45