【问题标题】:Lua: How do you update a variable that's in an event?Lua:你如何更新事件中的变量?
【发布时间】:2020-11-19 07:01:04
【问题描述】:

我遇到的问题是我的变量在事件发生后没有更新。这是我的代码:

local Players = game:GetService("Players")
local intermission = 15 -- time in seconds

local AmountOfPlayers = #Players:GetPlayers() -- starts at zero
local minPlayers = 1


Players.PlayerAdded:Connect(function(Player) -- updates amount of players in server
    AmountOfPlayers = AmountOfPlayers + 1
end)

Players.PlayerRemoving:Connect(function(Player) -- updates amount of players in server
    AmountOfPlayers = AmountOfPlayers - 1
end)

下面,这个 if 语句没有运行,因为 AmountOfPlayers 不等于 minPlayers。

while intermission > 0 do
    if AmountOfPlayers >= minPlayers then
    print("SUCCESS")                
    end
end

我有一个变量 AmountOfPlayers 的范围问题。我不知道如何解决这个问题,所以任何建议都将不胜感激。感谢您的帮助!

【问题讨论】:

  • 什么是中场休息?你的事件回调被触发了吗?
  • 使AmountOfPlayers 全局化。或者确保您的 while intermission 语句在本地 AmountOfPlayers 范围内
  • Players:GetPlayers() 已经是全球性的。为什么不在您需要检查游戏中有多少玩家时调用它?

标签: if-statement events lua scope roblox


【解决方案1】:

您忘记在 while 循环中添加 wait()。这很可能是导致脚本崩溃且无法正常工作的原因。所以它应该是这样的:

while intermission > 0 do
    wait()
    if AmountOfPlayers >= minPlayers then
    print("SUCCESS")                
    end
end

如果这不是问题,那么不要做:

local AmountOfPlayers = #Players:GetPlayers()

改为:

local AmountOfPlayers = Players:GetChildren()

并删除这两个函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-10
    • 2021-02-28
    • 2022-07-27
    • 2020-04-16
    • 2023-04-08
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多