我如何在 Roblox Lua 中的重复循环中等待

How can I wait in a repeat loop in Roblox Lua

game.Workspace.PetRooms.FireRoom.FireRoom.Floor.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.parent)
local char = hit.Parent -- Character
local hum = char:FindFirstChild("Humanoid") -- Humanoid
if hum then -- If humanoid then...
    if hum.Health ~= 0 and player.Team == game.Teams.Scientists then -- Makes sure that character is not dead; makes sure that character is a scientist
        repeat
            wait (10)
            hum.Health = hum.Health - 10 -- Kills the character slowly
        until hum.Health == 0
    end
    player.Team = game.Teams.Infected -- Changes the player's team to infected AFTER they die
end
end)

“wait(10)”应该在每“- 10”生命值之间等待 10 秒,但代码只等待 10 秒,然后快速杀死玩家。

除了GetPropertyChangedSignal我真的想不出别的了 也许试试

您已将此回调连接到 Touched 事件,每次玩家触摸该部件时都会触发该事件。如果玩家在地板上行走,每次玩家的脚碰到它都会开火。

可能发生的情况是此事件多次触发,并且您同时有一堆这些 repeat-while 循环 运行,导致玩家的生命值迅速下降。

我建议消除连接抖动,以便每个玩家只发生一个循环:

-- create a map of players touching the floor
local playersTouching = {}

local floor = game.Workspace.PetRooms.FireRoom.FireRoom.Floor
floor.Touched:Connect(function(hit)
    -- check that the thing that hit is a player
    local char = hit.Parent -- Character
    local hum = char:FindFirstChild("Humanoid") -- Humanoid
    if hum == nil then
        return
    end

    -- escape if this player is already touching the floor
    local playerName = char.Name
    if playersTouching[playerName] then
        return
    end

    -- the player was not touching before, so flip the debounce flag
    -- everything after this point happens once
    playerTouching[playerName] = true

    -- check if character is not dead and a scientist
    local player = game.Players:GetPlayerFromCharacter(hit.parent)
    local isScientist = player.Team == game.Teams.Scientists
    local isAlive = hum.Health > 0
    if isScientist and isAlive then
        -- start a loop to kill the player
        while hum.Health > 0 then
            wait(10)
            hum.Health = hum.Health - 10
        end

        -- Change the player's team to infected
        player.Team = game.Teams.Infected
    end

    -- clear the debounce flag
    playerTouching[playerName] = false
end)