A 디바운스 패턴은 함수가 너무 많이 실행되거나 입력이 여러 번 트리거되는 것을 방지하는 코딩 기술입니다.다음 스크립트 시나리오는 최선의 방법으로 debounce를 설명합니다.
충돌 감지
만약 당신이 만지면 10의 피해를 입히는 위험한 트랩 부품을 만들고 싶다고 가정해 보겠습니다.초기 구현은 기본 BasePart.Touched 연결과 이와 같은 기능 damagePlayer을 사용할 수 있습니다:
스크립트 - 플레이어 손상
local part = script.Parent
local function damagePlayer(otherPart)
print(part.Name .. " collided with " .. otherPart.Name)
local humanoid = otherPart.Parent:FindFirstChildWhichIsA("Humanoid")
if humanoid then
humanoid.Health -= 10 -- 플레이어 체력 줄이기
end
end
part.Touched:Connect(damagePlayer)
처음 보기에는 논리적이지만, 테스트는 미세한 물리적 충돌에 따라 빠른 연속으로 Touched 이벤트가 여러 번 발생한다는 것을 보여줍니다.

초기 문의과도한 피해를 유발하지 않으려면 인스턴스 특성을 통해 쿨다운 기간을 적용하는 디바운스 시스템을 추가할 수 있습니다.
스크립트 - 디바운스를 사용하여 플레이어에 피해 입히기
local part = script.Parent
local RESET_TIME = 1
local function damagePlayer(otherPart)
print(part.Name .. " collided with " .. otherPart.Name)
local humanoid = otherPart.Parent:FindFirstChildWhichIsA("Humanoid")
if humanoid then
if not part:GetAttribute("Touched") then
part:SetAttribute("Touched", true) -- 특성을 참으로 설정
humanoid.Health -= 10 -- 플레이어 체력 줄이기
task.wait(RESET_TIME) -- 재설정 기간 대기
part:SetAttribute("Touched", false) -- 특성 재설정
end
end
end
part.Touched:Connect(damagePlayer)
트리거 소리
소리 효과를 사용할 때도 디바운스는 유용합니다(Touched), 또는 사용자가 화면에 있는 버튼과 충돌할 때 소리를 재생하거나(Activated), 사용자가 화면에 있는 버튼과 상호작용할 때 Sound:Play() 를 호출하면 트랙의 시작부터 재생이 시작되고 — 지연 시스템 없이 — 소리가 빠른 연속으로 여러 번 재생될 수 있습니다.
음향 겹치기를 방지하려면 IsPlaying 개체의 Sound 속성을 사용하여 지연을 제거할 수 있습니다.
스크립트 - Debounce를 사용하여 충돌 소리 재생
local projectile = script.Parent
local function playSound()
-- 부품에서 자식 사운드 찾기
local sound = projectile:FindFirstChild("Impact")
-- 아직 재생되지 않는 경우에만 소리를 재생하십시오
if sound and not sound.IsPlaying then
sound:Play()
end
end
projectile.Touched:Connect(playSound)
스크립트 - 디바운스를 사용하여 플레이 버튼 클릭
local button = script.Parent
local function onButtonActivated()
-- 버튼에서 자식 사운드 찾기
local sound = button:FindFirstChild("Click")
-- 아직 재생되지 않는 경우에만 소리를 재생하십시오
if sound and not sound.IsPlaying then
sound:Play()
end
end
button.Activated:Connect(onButtonActivated)
픽업 효과
경험은 종종 의약품, 탄약 팩 및 기타와 같은 3D 세계의 수집품 획득을 포함합니다.이러한 픽업을 플레이어가 계속해서 잡을 수 있도록 디자인하는 경우, 픽업 새로 고침 및 재활성화 전에 "쿨다운" 시간이 추가되어야 합니다.
충돌 감지와 마찬가지로 인스턴스 특성을 사용하여 디바운스 상태를 관리하고, 부품의 을 변경하여 쿨다운 기간을 시각화할 수 있습니다.
스크립트 - 디바운스를 사용하여 상태 획득
local part = script.Parent
part.Anchored = true
part.CanCollide = false
local COOLDOWN_TIME = 5
local function healPlayer(otherPart)
local humanoid = otherPart.Parent:FindFirstChildWhichIsA("Humanoid")
if humanoid then
if not part:GetAttribute("CoolingDown") then
part:SetAttribute("CoolingDown", true) -- 특성을 참으로 설정
humanoid.Health += 25 -- 플레이어 건강 증가
part.Transparency = 0.75 -- 쿨다운 상태를 나타내기 위해 부품을 반투명하게 만들기
task.wait(COOLDOWN_TIME) -- 대기 시간 지연 기간 기다리기
part.Transparency = 0 -- 부품을 완전히 불투명하게 재설정
part:SetAttribute("CoolingDown", false) -- 특성 재설정
end
end
end
part.Touched:Connect(healPlayer)