Advertisement
apieceoffruit

Snippits: Cached Array

Sep 5th, 2021 (edited)
333
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.58 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using UnityEditor;
  4. using UnityEngine;
  5.  
  6.     public class CachedArray<T> : IEnumerable<T> where T : UnityEngine.Object
  7.     {
  8.         public static T[] GetAll(string query,
  9.             params string[] locations)  =>  
  10.             AssetDatabase.FindAssets(query, locations)  
  11.                 .Select(AssetDatabase.GUIDToAssetPath)  
  12.                 .Select(AssetDatabase.LoadAssetAtPath<T>)  
  13.                 .Where(x => x != null)  
  14.                 .ToArray();
  15.  
  16.         public static CachedArray<T> From(string query, params string[] locations) =>
  17.             new CachedArray<T>(() => GetAll(query, locations));
  18.  
  19.         public static CachedArray<T> From(Func<T[]> getter) => new CachedArray<T>(getter);
  20.  
  21.         public T[] All => _items;
  22.         public bool HasItems { get; private set; }
  23.  
  24.         public CachedArray(Func<T[]> getter) => _getter = getter;
  25.  
  26.         void LoadItems() => _items = _getter.Invoke();
  27.  
  28.         public T[] GetItems()
  29.         {
  30.             if (HasItems) return _items;
  31.             LoadItems();
  32.             return _items;
  33.         }
  34.  
  35.         public T this[int index]
  36.         {
  37.             get => GetItems()[index];
  38.             set => GetItems()[index] = value;
  39.         }
  40.  
  41.         public static implicit operator T[](CachedArray<T> cached) => cached.GetItems();
  42.  
  43.         T[] _items;
  44.         readonly Func<T[]> _getter;
  45.         public IEnumerator<T> GetEnumerator() => (IEnumerator<T>) _items.GetEnumerator();
  46.  
  47.         IEnumerator IEnumerable.GetEnumerator()
  48.         {
  49.             return GetEnumerator();
  50.         }
  51.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement