统一调用沉重功能时,避免游戏死机的最简单方法是什么?

时间:2019-09-28 15:30:44

标签: multithreading unity3d

我目前正在开发一种Metatic TAC Toe AI,可以在Unity中使用。每当玩家进行移动时,我都希望实例化粒子。但是,当调用AI的移动评估功能时,粒子冻结。在计算机计算最佳运动时,使粒子继续运动的最简单方法是什么?我已经阅读了有关统一Job系统的文档,但是Job结构不能包含引用类型,这是一个问题。

public void Play (List<Move> moves) {

    int[,] grid = gB.stateGrid;

    Move bestMove = new Move();
    if (firstTurn)
    {
        bestMove.col = 4;
        bestMove.row = 4;
        firstTurn = false;
    }
    else
    {

        foreach (Move m in moves)
        {

            int e = EvalMove(m, level, true, grid, gB.subgridsStates, Mathf.NegativeInfinity, Mathf.Infinity);

            m.value = e;
        }

        int best = moves.Select(x => x.value).Max();
        List<Move> bestMoves = moves.Where(x => x.value == best).ToList();
        bestMove = bestMoves[Random.Range(0, bestMoves.Count - 1)];

    }
    gB.PlaceToken(bestMove);
}

该函数计算所有可能动作中的bestMove,然后要求游戏板脚本将相应的标记放置在网格上。

1 个答案:

答案 0 :(得分:0)

您可以使用Coroutine完成繁重的任务并避免冻结。

将您的方法返回类型更改为IEnumerator

IEnumerator Heavy() 
{
    // some real heavy task
    for (int i = 1; i < 10000000; i++) 
    {
        balh();
        yield return new WaitForEndOfFrame();
    }
}

简单地这样称呼它:

StartCoroutine(Heavy());

您只需要在MonoBehaviour上运行它即可。就是这样。