yyl
9 天以前 51b0f6ed9f4e1d3bb6f8144470b46908c7699a96
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System.Collections.Generic;
using UnityEngine;
 
/// <summary>
/// WaitForSeconds缓存,避免每次yield时分配GC
/// 使用方式:yield return WaitForSecondsCache.Get(1f);
/// </summary>
public static class WaitForSecondsCache
{
    private static readonly Dictionary<float, WaitForSeconds> _cache = new Dictionary<float, WaitForSeconds>();
 
    public static WaitForSeconds Get(float seconds)
    {
        if (!_cache.TryGetValue(seconds, out var wait))
        {
            wait = new WaitForSeconds(seconds);
            _cache[seconds] = wait;
        }
        return wait;
    }
 
    // 预缓存常用值
    public static readonly WaitForSeconds Wait0_1 = new WaitForSeconds(0.1f);
    public static readonly WaitForSeconds Wait0_5 = new WaitForSeconds(0.5f);
    public static readonly WaitForSeconds Wait1 = new WaitForSeconds(1f);
    public static readonly WaitForSeconds Wait2 = new WaitForSeconds(2f);
    public static readonly WaitForSeconds Wait5 = new WaitForSeconds(5f);
}