You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CoreGames自定义WaitUntil协程函数主代码调用失效问题咨询

结论

你的猜想完全成立,问题确实和代码的调用位置直接相关。

异常原因

  1. Core Games 运行环境限制:脚本的顶层主代码(非事件回调、Task.Spawn 触发的执行逻辑)运行在 Lua 的主协程中,该协程默认不支持挂起操作。你在主代码中直接调用 _G.WaitUntil 执行 coroutine.yield 时,会直接中断当前执行流,因此后续的 Task.Wait(5)、Game.StartRound() 完全不会运行。
  2. _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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:24:02