触摸零件时每秒获取领导者统计数据

问题描述 投票:0回答:1

我一直在尝试编写一个代码,让触摸某个部件的玩家每秒获得领导统计数据,但由于某种原因,玩家每秒获得多个统计数据。我希望玩家在停止触摸该零件时停止获得积分。

这是我的代码:

local part = script.Parent
local canGet = true
local function onTouch(otherPart)

    local humanoid = otherPart.Parent:FindFirstChild('Humanoid')

    if humanoid then

        local player = game.Players:FindFirstChild(otherPart.Parent.Name)

        while player and canGet do

            wait(1)

            player.leaderstats.Jump.Value = player.leaderstats.Jump.Value + 1
            


        end

    end

end



part.Touched:Connect(onTouch)

我只想让玩家每秒获得 1 个领导者统计数据。谢谢

roblox
1个回答
0
投票

在您的代码中,

onTouch
函数每秒将被触发多次。然后,您创建一个将永远运行多次的循环。

实现解决方案的一种方法是使用去抖变量来阻止

onTouch
功能,使其每秒仅激活一次。

我将在这里使用您的 canGet 变量作为去抖动变量:

local part = script.Parent
local canGet = true
local function onTouch(otherPart)
    if canGet==false then 
       return --If our cooldown is still active, do nothing and stop the function
    end
    local humanoid = otherPart.Parent:FindFirstChild('Humanoid')

    if humanoid then

        local player = game.Players:FindFirstChild(otherPart.Parent.Name)

        player.leaderstats.Jump.Value = player.leaderstats.Jump.Value + 1
        canGet = false --We block other executions of the function
        wait(1)
        canGet = true --We waited one second, we can now allow the player to get  more points

    end

end



part.Touched:Connect(onTouch)
© www.soinside.com 2019 - 2024. All rights reserved.