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

game.Workspace.PetRooms.FireRoom.FireRoom.Floor.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.parent)
local char = hit.Parent -- 角色
local hum = char:FindFirstChild("Humanoid") -- 人形
if hum then -- 如果有人形...
    if hum.Health ~= 0 and player.Team == game.Teams.Scientists then -- 确保角色未死亡;确保角色是科学家
        repeat
            wait (10)
            hum.Health = hum.Health - 10 -- 缓慢杀死角色
        until hum.Health == 0
    end
    player.Team = game.Teams.Infected -- 在死后将玩家的团队更改为感染
end
end)

"wait(10)" 被设计为在每次 "- 10" 生命值的间隔中等待 10 秒,但实际代码会快速杀死玩家。

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

点赞
stackoverflow用户16200945
stackoverflow用户16200945

我真的想不出除了GetPropertyChangedSignal以外的东西。 或许可以试试这个。

2021-12-31 02:34:07
stackoverflow用户2860267
stackoverflow用户2860267

你将这个回调函数连接到了 Touched 事件上,每当一个玩家碰触到这个部件时,该事件就会被激活。如果玩家在地板上行走,每当玩家的脚碰到地面时,该事件都会被激活。

问题很可能是这个事件被多次激活了,而且你同时有一堆这样的重复循环在运行,导致玩家的生命值非常快地下降。

我建议去抖动连接,这样每个玩家只会发生一次循环:

-- 创建一个地图来记录触碰地面的玩家
local playersTouching = {}

local floor = game.Workspace.PetRooms.FireRoom.FireRoom.Floor
floor.Touched:Connect(function(hit)
    -- 确认击中的东西是玩家
    local char = hit.Parent -- 角色
    local hum = char:FindFirstChild("Humanoid") -- 人形
    if hum == nil then
        return
    end

    -- 如果这个玩家已经在触碰地面了,则退出
    local playerName = char.Name
    if playersTouching[playerName] then
        return
    end

    -- 这个玩家之前没有触碰地面,所以翻转去抖动标记
    -- 之后的所有操作只会发生一次
    playerTouching[playerName] = true

    -- 检查这个角色是否还活着而且是科学家
    local player = game.Players:GetPlayerFromCharacter(hit.parent)
    local isScientist = player.Team == game.Teams.Scientists
    local isAlive = hum.Health > 0
    if isScientist and isAlive then
        -- 开始一个循环以杀死玩家
        while hum.Health > 0 do
            wait(10)
            hum.Health = hum.Health - 10
        end

        -- 将玩家的队伍更改为感染者
        player.Team = game.Teams.Infected
    end

    -- 清空去抖动标记
    playerTouching[playerName] = false
end)
2021-12-31 22:38:11