Roblox运行奔跑FOV切换脚本报Script Timeout错误游戏冻结如何修复
问题修复方案
错误根源
你遇到的Script Timeout: exhausted allowed execution time报错、游戏冻结的问题,完全由代码中两段无等待空循环导致:
repeat until not Running
这类没有任何等待逻辑的空循环会持续占用线程执行资源,瞬间耗尽Roblox分配给脚本的运行时间,直接触发超时崩溃。这两段循环逻辑和你要实现的奔跑FOV效果没有任何关联,属于冗余代码,可以直接删除。
额外逻辑修复
删除空循环之外,你的原有代码还存在几处逻辑问题需要调整:
- 原有按下Shift的判断逻辑中,如果玩家已经处于奔跑状态,会先执行减速、切回普通FOV,又立刻执行加速、切奔跑FOV,属于无效逻辑,会导致WalkSpeed数值异常
- 没有监听左Shift松开的事件,无法实现松开Shift就停止奔跑的常规交互
- HumanoidRootPart没有提前缓存,每次触发输入事件都调用
WaitForChild存在冗余开销
修复后完整代码
local UserInputService = game:GetService("UserInputService") local TweenService = game:GetService("TweenService") local player = game.Players.LocalPlayer local Character = script.Parent local Humanoid = Character:WaitForChild("Humanoid") local HumanoidRootPart = Character:WaitForChild("HumanoidRootPart") local Camera = workspace.CurrentCamera local FovRun = TweenService:Create(Camera, TweenInfo.new(0.5), {FieldOfView = 75}) local FovWalk = TweenService:Create(Camera, TweenInfo.new(0.5), {FieldOfView = 70}) local Running = false local DEFAULT_WALKSPEED = Humanoid.WalkSpeed -- 缓存初始移速避免数值累加错误 -- 按下左Shift触发奔跑 UserInputService.InputBegan:Connect(function(Key, IsTyping) if Key.KeyCode == Enum.KeyCode.LeftShift and not IsTyping and Humanoid.Health > 0 then -- 只有向前移动时才触发奔跑 if Humanoid.MoveDirection:Dot(HumanoidRootPart.CFrame.LookVector) > 0 and not Running then Running = true Humanoid.WalkSpeed = DEFAULT_WALKSPEED + 8 FovRun:Play() end end end) -- 松开左Shift停止奔跑 UserInputService.InputEnded:Connect(function(Key, IsTyping) if Key.KeyCode == Enum.KeyCode.LeftShift and not IsTyping and Running then Running = false Humanoid.WalkSpeed = DEFAULT_WALKSPEED FovWalk:Play() end end) -- 额外兼容:玩家停止移动、死亡时自动退出奔跑状态 Humanoid.Running:Connect(function(Speed) if Speed < 1 and Running then Running = false Humanoid.WalkSpeed = DEFAULT_WALKSPEED FovWalk:Play() end end) Humanoid.Died:Connect(function() if Running then Running = false Humanoid.WalkSpeed = DEFAULT_WALKSPEED FovWalk:Play() end end)
内容的提问来源于stack exchange,提问作者SandStorm
相关产品推荐
相关产品推荐

