UniTask/Unity的PlayerLoopTiming触发顺序

时间:2024-11-10 21:14:57

开始尝试在项目中使用UniTask,发现其中的UniTask.Yield确实很好用,还可以传入PlayerLoopTiming来更细致的调整代码时机,不过平常在Mono中接触的只有Awake,Start,Update等常用Timing,其他的就没怎么接触了,虽然看名字也大概能明白,但姑且还是测试一下。

测试代码:

using UnityEngine;
using System;
using Cysharp.Threading.Tasks;
public class TestScript : MonoBehaviour{
    bool logTiming = false;
    async UniTaskVoid TestPlayerLoop(PlayerLoopTiming timing) {
        await UniTask.Yield(timing);
        Debug.Log($"{timing} -> {Time.frameCount}");
    }
    private void Awake() {
        logTiming = true;
        foreach (PlayerLoopTiming timing in Enum.GetValues(typeof(PlayerLoopTiming))) {
            //跳过FixUpdate的,因为触发时间可以在Setting里调整,和单帧的逻辑不太一样
            if (timing == PlayerLoopTiming.FixedUpdate) { 
                continue;
            }
            if (timing == PlayerLoopTiming.LastFixedUpdate) {
                continue;
            }
            TestPlayerLoop(timing).Forget();
        }
        if (logTiming) {
            Debug.Log($"TestScript Awake -> {Time.frameCount}");
        }
    }
    private void OnEnable() {
        if (logTiming) {
            Debug.Log($"TestScript OnEnable -> {Time.frameCount}");
        }
    }
    void Start()
    {
        if (logTiming) {
            Debug.Log($"TestScript Start -> {Time.frameCount}");
        }
    }
    void Update()
    {
        if (logTiming) {
            Debug.Log($"TestScript Update -> {Time.frameCount}");
        }
    }
    private void LateUpdate() {
        if (logTiming) {
            Debug.Log($"TestScript LateUpdate -> {Time.frameCount}");
            logTiming = false;
        }
    }
}

结果:

和猜想也大差不差就是了