Roblox冲刺Tool冷却失效求助:玩家无法重复触发技能
冲刺技能冷却失效无法复用的问题排查与修复
核心问题原因
你的代码存在两个关键问题导致冷却锁死:
- Sound实例被销毁后未重新创建:你提前在全局作用域创建了
sound变量,第一次触发技能后执行sound:Destroy(),这个变量就指向了已销毁的无效对象。第二次按E时,尝试给sound.Parent赋值会直接抛出错误,中断整个函数执行,后续的wait(5)和Cooldown = false永远不会运行,冷却状态一直锁死在true。 - 缺少容错处理:没有对
Character或Humanoid做判空检查,如果玩家角色未加载完成就触发技能,同样会报错中断代码流程。
修复方案
方案1:每次触发技能时创建新的Sound实例
把Sound的创建逻辑移到技能触发代码块内,每次使用生成新实例,避免复用已销毁对象:
-- Locals -- local Tool = script.Parent local Cooldown = false local mouse = game.Players.LocalPlayer:GetMouse() -- Main Script -- mouse.KeyDown:Connect(function(key) -- 兼容大小写输入 if key:lower() == "e" then if not Cooldown then Cooldown = true -- 每次触发创建新的Sound实例 local sound = Instance.new("Sound") sound.Parent = Tool.Handle sound.Volume = 3 sound.SoundId = "rbxassetid://9079020013" sound:Play() -- 判空避免角色加载问题报错 local humanoid = game.Players.LocalPlayer.Character:FindFirstChildOfClass("Humanoid") if humanoid then humanoid.WalkSpeed = 60 end wait(0.5) if humanoid then humanoid.WalkSpeed = 16 end -- 销毁本次创建的Sound sound:Destroy() wait(5) -- 重置冷却 Cooldown = false end end end)
方案2:复用Sound实例(更高效)
如果不想反复创建销毁对象,可以提前把Sound挂载到Tool的Handle下,每次使用时重置播放状态:
-- Locals -- local Tool = script.Parent local Cooldown = false local mouse = game.Players.LocalPlayer:GetMouse() -- 提前创建Sound并挂载到Handle,不销毁 local sound = Instance.new("Sound") sound.Parent = Tool.Handle sound.Volume = 3 sound.SoundId = "rbxassetid://9079020013" -- Main Script -- mouse.KeyDown:Connect(function(key) if key:lower() == "e" then if not Cooldown then Cooldown = true -- 先停止再播放,避免音效叠加 sound:Stop() sound:Play() local humanoid = game.Players.LocalPlayer.Character:FindFirstChildOfClass("Humanoid") if humanoid then humanoid.WalkSpeed = 60 end wait(0.5) if humanoid then humanoid.WalkSpeed = 16 end wait(5) Cooldown = false end end end)
额外优化建议
改用UserInputService替代mouse.KeyDown:mouse.KeyDown是Roblox旧API,已被官方标记为废弃,UserInputService能提供更可靠的输入检测,还能过滤UI交互时的误触:
local UserInputService = game:GetService("UserInputService") local Players = game:GetService("Players") local Tool = script.Parent local Cooldown = false local localPlayer = Players.LocalPlayer UserInputService.InputBegan:Connect(function(input, gameProcessed) -- 忽略UI操作时的按键输入 if gameProcessed then return end if input.KeyCode == Enum.KeyCode.E then if not Cooldown then Cooldown = true local sound = Instance.new("Sound") sound.Parent = Tool.Handle sound.Volume = 3 sound.SoundId = "rbxassetid://9079020013" sound:Play() local character = localPlayer.Character if character then local humanoid = character:FindFirstChildOfClass("Humanoid") if humanoid then humanoid.WalkSpeed = 60 end end wait(0.5) if character then local humanoid = character:FindFirstChildOfClass("Humanoid") if humanoid then humanoid.WalkSpeed = 16 end end sound:Destroy() wait(5) Cooldown = false end end end)
内容的提问来源于stack exchange,提问作者your average roblox dev lol
相关产品推荐
相关产品推荐

