CoreGames自定义WaitUntil协程函数主代码调用失效问题咨询
结论
你的猜想完全成立,问题确实和代码的调用位置直接相关。
异常原因
- Core Games 运行环境限制:脚本的顶层主代码(非事件回调、Task.Spawn 触发的执行逻辑)运行在 Lua 的主协程中,该协程默认不支持挂起操作。你在主代码中直接调用
_G.WaitUntil执行coroutine.yield时,会直接中断当前执行流,因此后续的Task.Wait(5)、Game.StartRound()完全不会运行。 _G.WaitUntil自身校验逻辑缺陷:函数仅判断了coroutine.running()是否有返回值,没有增加协程可挂起性校验。事件回调、Task.Spawn 创建的协程调用coroutine.isyieldable()会返回 true 可正常挂起,而主协程调用该接口会返回 false,直接执行 yield 必然触发异常。
另外你原代码中变量名tread为拼写错误,正确拼写为thread。
修复方案
第一步:优化 _G.WaitUntil 校验逻辑
-- Yields the current thread until the condition returns true checking every 'interval' seconds function _G.WaitUntil(condition, interval) if not interval then interval = 1/60 end local thread = coroutine.running() -- 增加可挂起校验,提前抛出可读错误 if not thread or not coroutine.isyieldable() then error("WaitUntil can only be called in yieldable scenarios: event callback, Task.Spawn", 2) end local function check() if condition() then coroutine.resume(thread) else Task.Spawn(check, interval) end end Task.Spawn(check, interval) coroutine.yield(thread) end
第二步:修改主代码的调用逻辑
将需要挂起的逻辑包裹在 Task.Spawn 中,创建可挂起协程运行:
Game.playerJoinedEvent:Connect(function (player) if _G.IsInRound then Task.Wait(1) Events.BroadcastToAllPlayers("Show the select UI", player) end end) -- 用Task.Spawn创建可挂起协程运行等待逻辑 Task.Spawn(function() _G.WaitUntil(function () return #Game.GetPlayers() > 0 end, 1) Task.Wait(5) Game.StartRound() end)
内容的提问来源于stack exchange,提问作者HerlySQR
相关产品推荐
相关产品推荐

