脚本无法更新食物条UI - Roblox Studio

首先,我有

playerStats(模块脚本)game.StarterPlayer.StarterCharacterScripts

local module = {}

module.hunger = 0
module.thirst = 100

return module

为了防止您开始失去健康,饥饿值或口渴值必须高于0。现在我将其设置为零,以便我可以测试我制作的食品项目,该项目应该增加20个饥饿值。它确实有效,并停止了健康损失,但它不会更新foodBar UI。(我暂时还没有关于口渴的任何东西)。

我为更新屏幕和食品项目编写的脚本是:

食品项目(服务器端)workspace.Food.ClickDetector

local food = script.Parent.Parent
local PlayerStats = require(game.StarterPlayer.StarterCharacterScripts.playerStats)
local gain = 2
local playerFunctions = require(game.StarterPlayer.StarterCharacterScripts.playerFunctions)

script.Parent.MouseClick:Connect(function()
    food:remove()
    PlayerStats.hunger+=gain
    print("Food on click : " .. PlayerStats.hunger)
    playerFunctions.updateFood()
end)

更新食品条(模块脚本)game.StarterPlayer.StarterCharacterScripts

local module = {}

module.updateFood = function()
    local gui = game.StarterGui.ScreenGui
    local PlayerStats = require(game.StarterPlayer.StarterCharacterScripts.playerStats)
    gui.foodBar.Text = "Hunger: " .. PlayerStats.hunger
end

return module

我不认为是更新foodBar的函数的问题,因为它在我的其他脚本中用于检查玩家状态时可以正常工作。

local data = require(game.StarterPlayer.StarterCharacterScripts.playerStats)
local player = script.Parent
local humanoid = player:WaitForChild("Humanoid");
local playerFunctions = require(script.Parent.playerFunctions)

task.spawn(function()
    while data.hunger <= 0 or data.thirst <= 0 do
        wait(0.1)
        humanoid.Health-=1
    end
end)

humanoid.Died:Connect(function()
    data.hunger = 100
    data.thirst = 100
end)

while true do
    wait(0.1)
    playerFunctions.updateFood()
end

是的,我知道我在这里放了很多代码,但我对Lua非常陌生,不知道可能是什么,所以我希望您能看到所有东西,以防出现意外情况。

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

点赞
stackoverflow用户16667848
stackoverflow用户16667848

原文如下:

The reason why the hunger bar does not update is because you're updating StarterGui (the instance that gives out the Gui) instead of PlayerGui (PlayerGui is inside the Player's instance)

Also, don't update the playerStats module inside StarterPlayer, it will give those stats to all players. Instead, update the module inside of PlayerScripts (which is also located inside of the Player's instance) and require that module instead.

翻译结果如下:

饥饿值条不更新的原因是因为你更新了 StarterGui(提供 GUI 的实例)而不是 PlayerGui(PlayerGui 在玩家实例内部)。

另外,不要更新 StarterPlayer 内的 playerStats 模块,它会把这些状态授予所有玩家。相反,更新 PlayerScripts 内的模块(它也位于玩家实例内部)并要求该模块。

2021-10-20 17:12:56