Unity 协程GC优化记录

第一种 缓存

csharp 复制代码
public static class WaitCache
{
    private static readonly Dictionary<float, WaitForSeconds> _cache = new();
    
    public static WaitForSeconds Get(float seconds)
    {
        if (!_cache.TryGetValue(seconds, out var wait))
        {
            wait = new WaitForSeconds(seconds);
            _cache[seconds] = wait;
        }
        return wait;
    }
}

第二种 零GC优化版

csharp 复制代码
using System.Collections;
using UnityEngine;

namespace GameScripts.Common
{
    /// <summary>
    /// 协程等待工具 - 零GC优化版
    /// </summary>
    public static class CoroutineUtility
    {
        // ==================== 工厂方法 ====================
        public static WaitTime Wait(float seconds) => new WaitTime(seconds);
        public static WaitRealtime WaitReal(float seconds) => new WaitRealtime(seconds);
        public static WaitFrames Frames(int count) => new WaitFrames(count);

        // ==================== 基于 Time.time(受TimeScale影响)====================
        public readonly struct WaitTime : IEnumerator
        {
            private readonly float _endTime;

            public WaitTime(float seconds)
            {
                _endTime = Time.time + seconds;
            }

            public bool MoveNext() => Time.time < _endTime;
            public void Reset() { }
            public object Current => null;
        }

        // ==================== 基于真实时间(不受TimeScale影响)====================
        public readonly struct WaitRealtime : IEnumerator
        {
            private readonly float _endTime;

            public WaitRealtime(float seconds)
            {
                _endTime = Time.realtimeSinceStartup + seconds;
            }

            public bool MoveNext() => Time.realtimeSinceStartup < _endTime;
            public void Reset() { }
            public object Current => null;
        }

        // ==================== 按帧等待(修复版)====================
        public readonly struct WaitFrames : IEnumerator
        {
            private readonly int _targetFrame;

            public WaitFrames(int frames)
            {
                _targetFrame = Time.frameCount + frames;
            }

            public bool MoveNext() => Time.frameCount < _targetFrame;
            public void Reset() { }
            public object Current => null;
        }

        // ==================== 条件等待(注意:lambda 有 GC)====================
        public readonly struct WaitUntil : IEnumerator
        {
            private readonly System.Func<bool> _predicate;

            public WaitUntil(System.Func<bool> predicate)
            {
                _predicate = predicate;
            }

            public bool MoveNext() => !_predicate();
            public void Reset() { }
            public object Current => null;
        }

        public readonly struct WaitWhile : IEnumerator
        {
            private readonly System.Func<bool> _predicate;

            public WaitWhile(System.Func<bool> predicate)
            {
                _predicate = predicate;
            }

            public bool MoveNext() => _predicate();
            public void Reset() { }
            public object Current => null;
        }
    }
}
相关推荐
小马爱打代码1 天前
Spring AI 实战:Agent 基础搭建与核心能力解析
java·人工智能·spring
csdn2015_1 天前
springboot task
java·spring boot·后端
czlczl200209251 天前
Spring Boot :如何高性能地在 Filter 中获取响应体(Response Body)
java·spring boot·后端
sg_knight1 天前
抽象工厂模式(Abstract Factory)
java·python·设计模式·抽象工厂模式·开发
春日见1 天前
win11 分屏设置
java·开发语言·驱动开发·docker·单例模式·计算机外设
2301_780029041 天前
支付宝sdk导入错误
java·开发语言·maven
码界奇点1 天前
基于Spring Boot和Vue3的无头内容管理系统设计与实现
java·spring boot·后端·vue·毕业设计·源代码管理
九皇叔叔1 天前
【03】微服务系列 之Nacos 注册中心(服务注册)
java·微服务·nacos·架构·注册中心·服务注册
木辰風1 天前
PLSQL自定义自动替换(AutoReplace)
java·数据库·sql
heartbeat..1 天前
Redis 中的锁:核心实现、类型与最佳实践
java·数据库·redis·缓存·并发