├── .gitattributes ├── .gitignore ├── CHANGELOG.md ├── CHANGELOG.md.meta ├── Documentation.meta ├── Documentation ├── com.gameframe.assetcache.md └── com.gameframe.assetcache.md.meta ├── Editor.meta ├── Editor ├── AssetCacheEditor.cs ├── AssetCacheEditor.cs.meta ├── com.gameframe.assetcache.Editor.asmdef └── com.gameframe.assetcache.Editor.asmdef.meta ├── LICENSE ├── LICENSE.md ├── LICENSE.md.meta ├── LICENSE.meta ├── README.md ├── README.md.meta ├── Runtime.meta ├── Runtime ├── AssetCache.cs ├── AssetCache.cs.meta ├── IAssetLoader.cs ├── IAssetLoader.cs.meta ├── RawImageWebAssetCache.cs ├── RawImageWebAssetCache.cs.meta ├── WebTextureCache.cs ├── WebTextureCache.cs.meta ├── com.gameframe.assetcache.asmdef └── com.gameframe.assetcache.asmdef.meta ├── Tests.meta ├── Tests ├── Editor.meta ├── Editor │ ├── AssetCacheEditorTests.cs │ ├── AssetCacheEditorTests.cs.meta │ ├── com.gameframe.assetcache.Editor.Tests.asmdef │ └── com.gameframe.assetcache.Editor.Tests.asmdef.meta ├── Runtime.meta └── Runtime │ ├── AssetCacheTests.cs │ ├── AssetCacheTests.cs.meta │ ├── com.gameframe.assetcache.Tests.asmdef │ └── com.gameframe.assetcache.Tests.asmdef.meta ├── package.json └── package.json.meta /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # This .gitignore file should be placed at the root of your Unity project directory 2 | # 3 | # Get latest from https://github.com/github/gitignore/blob/master/Unity.gitignore 4 | # 5 | /[Ll]ibrary/ 6 | /[Tt]emp/ 7 | /[Oo]bj/ 8 | /[Bb]uild/ 9 | /[Bb]uilds/ 10 | /[Ll]ogs/ 11 | /[Mm]emoryCaptures/ 12 | 13 | # Never ignore Asset meta data 14 | !/[Aa]ssets/**/*.meta 15 | 16 | # Uncomment this line if you wish to ignore the asset store tools plugin 17 | # /[Aa]ssets/AssetStoreTools* 18 | 19 | # TextMesh Pro files 20 | [Aa]ssets/TextMesh*Pro/ 21 | 22 | # Autogenerated Jetbrains Rider plugin 23 | [Aa]ssets/Plugins/Editor/JetBrains* 24 | 25 | # Visual Studio cache directory 26 | .vs/ 27 | 28 | # Gradle cache directory 29 | .gradle/ 30 | 31 | # Autogenerated VS/MD/Consulo solution and project files 32 | ExportedObj/ 33 | .consulo/ 34 | *.csproj 35 | *.unityproj 36 | *.sln 37 | *.suo 38 | *.tmp 39 | *.user 40 | *.userprefs 41 | *.pidb 42 | *.booproj 43 | *.svd 44 | *.pdb 45 | *.mdb 46 | *.opendb 47 | *.VC.db 48 | 49 | # Unity3D generated meta files 50 | *.pidb.meta 51 | *.pdb.meta 52 | *.mdb.meta 53 | 54 | # Unity3D generated file on crash reports 55 | sysinfo.txt 56 | 57 | # Builds 58 | *.apk 59 | *.unitypackage 60 | 61 | # Crashlytics generated file 62 | crashlytics-build.properties 63 | 64 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Created 9/18/2019 -------------------------------------------------------------------------------- /CHANGELOG.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 37f9667b99f5945039007c5f070a5712 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Documentation.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 04ca42ef7a6e84a79be4f90e02d3bf1b 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Documentation/com.gameframe.assetcache.md: -------------------------------------------------------------------------------- 1 | Asset cache library -------------------------------------------------------------------------------- /Documentation/com.gameframe.assetcache.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: c0a010b82e6ce4fddb4baa65b656f090 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Editor.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 2035fd51bfbdd4886a467f9503538c68 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Editor/AssetCacheEditor.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | namespace Gameframe.AssetCache.Editor 6 | { 7 | public class AssetCacheEditor : UnityEditor.Editor 8 | { 9 | } 10 | } 11 | 12 | 13 | -------------------------------------------------------------------------------- /Editor/AssetCacheEditor.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: a12a294208f464dc1817b776da4b3940 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Editor/com.gameframe.assetcache.Editor.asmdef: -------------------------------------------------------------------------------- 1 | { "name": "com.gameframe.assetcache.Editor", "references": [ "com.gameframe.assetcache" ], "optionalUnityReferences": [], "includePlatforms": [ "Editor" ], "excludePlatforms": [] } -------------------------------------------------------------------------------- /Editor/com.gameframe.assetcache.Editor.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d2a0879a686f54575a2d077ff4d30dc1 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Cory Leach 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright 2019 -------------------------------------------------------------------------------- /LICENSE.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f3c86f93f6d364ef5865d038f889c148 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /LICENSE.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 35b86c79644824eeaaaad006a8122884 3 | DefaultImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 |

Gameframe.AssetCache 👋

5 | 6 | 27 | 28 | Library for caching and unloading assets 29 | 30 | ## Quick Package Install 31 | 32 | #### Using UnityPackageManager (for Unity 2019.3 or later) 33 | Open the package manager window (menu: Window > Package Manager)
34 | Select "Add package from git URL...", fill in the pop-up with the following link:
35 | https://github.com/coryleach/UnityAssetCache.git#1.3.0
36 | 37 | #### Using UnityPackageManager (for Unity 2019.1 or later) 38 | 39 | Find the manifest.json file in the Packages folder of your project and edit it to look like this: 40 | ```js 41 | { 42 | "dependencies": { 43 | "com.gameframe.assetcache": "https://github.com/coryleach/UnityAssetCache.git#1.3.0", 44 | ... 45 | }, 46 | } 47 | ``` 48 | 49 | 50 | ## Usage 51 | 52 | ```c# 53 | //Create an asset cache (like a WebTextureCache) 54 | var cache = new WebTextureCache(); 55 | 56 | //Get a cached asset asynchronously 57 | var cachedAsset = await cache.GetAsync(url); 58 | 59 | //Use the asset 60 | image.texture = cachedAsset.Asset; 61 | 62 | //Dispose the reference so the cache knows you no longer are using it 63 | cachedAsset.Dispose(); 64 | cachedAsset = null; 65 | 66 | //Clean the cache so all assets with zero references are unloaded 67 | cache.ClearUnusedAssets(); 68 | ``` 69 | 70 | 71 | ## Author 72 | 73 | 👤 **Cory Leach** 74 | 75 | * Twitter: [@coryleach](https://twitter.com/coryleach) 76 | * Github: [@coryleach](https://github.com/coryleach) 77 | 78 | 79 | ## Show your support 80 | Give a ⭐️ if this project helped you! 81 |
82 | Please consider supporting it either by contributing to the Github projects (submitting bug reports or features and/or creating pull requests) or by buying me coffee using any of the links below. Every little bit helps! 83 |
84 | 85 | [![ko-fi](https://www.ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/coryleach) 86 | 87 | 88 | *** 89 | _This README was generated with ❤️ by [Gameframe.Packages](https://github.com/coryleach/unitypackages)_ 90 | -------------------------------------------------------------------------------- /README.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: acf0294874c794cdfa376d6f6696d6fa 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Runtime.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d83f3052336394294ba6bad2d2b22654 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Runtime/AssetCache.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace Gameframe.AssetCache 7 | { 8 | /// 9 | /// Maintains a cache of assets 10 | /// 11 | /// The kind of asset to be cached 12 | public class AssetCache : KeyedAssetCache where TAssetType : class 13 | { 14 | public AssetCache(IKeyedAssetLoader loader) : base(loader) { } 15 | } 16 | 17 | /// 18 | /// Maintains a cache of assets with a specified key type and asset type 19 | /// 20 | /// The kind of asset to be cached 21 | /// The key used to reference the asset to be loaded/unloaded 22 | public class KeyedAssetCache where TAssetType : class 23 | { 24 | /// 25 | /// Reference to a cached asset. 26 | /// Dispose() should be called to release the asset reference. 27 | /// 28 | public interface ICachedAsset : IDisposable 29 | { 30 | ICachedAsset Clone(); 31 | TAssetType Asset { get; } 32 | int RefCount { get; } 33 | } 34 | 35 | protected class AssetCacheEntry : IDisposable 36 | { 37 | private readonly TKeyType _assetKey; 38 | public TKeyType AssetKey => _assetKey; 39 | 40 | private int _refCount = 0; 41 | public int RefCount => _refCount; 42 | 43 | public TAssetType Asset => _task?.Result; 44 | 45 | private Task _task; 46 | public Task Task => _task; 47 | 48 | private readonly Action _assetDestroyer; 49 | 50 | private bool _disposed = false; 51 | 52 | public AssetCacheEntry(TKeyType assetKey, Task getAssetTask, Action assetDestroyer) 53 | { 54 | _assetKey = assetKey; 55 | _assetDestroyer = assetDestroyer; 56 | _task = getAssetTask; 57 | } 58 | 59 | public CachedAsset GetCachedAsset() 60 | { 61 | if (_disposed) 62 | { 63 | throw new InvalidOperationException("AssetCacheEntry cannot get asset after dispose."); 64 | } 65 | return new CachedAsset(this); 66 | } 67 | 68 | public void Increment() 69 | { 70 | if (_disposed) 71 | { 72 | throw new InvalidOperationException("AssetCacheEntry cannot increment after dispose."); 73 | } 74 | _refCount++; 75 | } 76 | 77 | public void Decrement() 78 | { 79 | if (_disposed) 80 | { 81 | throw new InvalidOperationException("AssetCacheEntry cannot decrement after dispose."); 82 | } 83 | _refCount--; 84 | } 85 | 86 | public void Dispose() 87 | { 88 | if (_disposed) 89 | { 90 | throw new InvalidOperationException("AssetCacheEntry already disposed"); 91 | } 92 | _disposed = true; 93 | if (!_task.IsCompleted) 94 | { 95 | _task.ContinueWith((assetTask) => { _assetDestroyer(assetTask.Result); }, TaskContinuationOptions.OnlyOnRanToCompletion); 96 | } 97 | else 98 | { 99 | _assetDestroyer(_task.Result); 100 | } 101 | _task = null; 102 | } 103 | } 104 | 105 | protected class CachedAsset : ICachedAsset 106 | { 107 | private readonly AssetCacheEntry _cacheEntry; 108 | private bool _disposed; 109 | 110 | public CachedAsset(AssetCacheEntry entry) 111 | { 112 | _disposed = false; 113 | _cacheEntry = entry; 114 | _cacheEntry.Increment(); 115 | } 116 | 117 | public ICachedAsset Clone() 118 | { 119 | return new CachedAsset(_cacheEntry); 120 | } 121 | 122 | public TAssetType Asset 123 | { 124 | get 125 | { 126 | if (_disposed) 127 | { 128 | throw new InvalidOperationException("CachedAsset has been disposed"); 129 | } 130 | return _cacheEntry.Asset; 131 | } 132 | } 133 | 134 | public int RefCount => _cacheEntry.RefCount; 135 | 136 | public void Dispose() 137 | { 138 | if (_disposed) 139 | { 140 | throw new InvalidOperationException("CachedAsset has already been disposed"); 141 | } 142 | _disposed = true; 143 | _cacheEntry.Decrement(); 144 | } 145 | } 146 | 147 | protected readonly Dictionary CacheDictionary = new Dictionary(); 148 | 149 | private readonly IKeyedAssetLoader _assetLoader; 150 | 151 | private async Task LocateAssetAsync(TKeyType assetKey) 152 | { 153 | var asset = await _assetLoader.LoadAsync(assetKey); 154 | return asset; 155 | } 156 | 157 | /// 158 | /// AssetCache Constructor 159 | /// 160 | /// loads and unloads assets 161 | public KeyedAssetCache(IKeyedAssetLoader loader) 162 | { 163 | _assetLoader = loader; 164 | } 165 | 166 | /// 167 | /// Get Cached Asset 168 | /// 169 | /// Key for the given asset. Should be handle-able by the asset locator 170 | /// Task that returns the cached asset 171 | public async Task GetAsync(TKeyType assetKey) 172 | { 173 | //Get or create cache entry 174 | if (!CacheDictionary.TryGetValue(assetKey, out var entry)) 175 | { 176 | entry = new AssetCacheEntry(assetKey, LocateAssetAsync(assetKey), _assetLoader.Unload); 177 | CacheDictionary.Add(assetKey, entry); 178 | } 179 | 180 | //Wait for the task to finish 181 | if (!entry.Task.IsCompleted) 182 | { 183 | await entry.Task; 184 | } 185 | 186 | return entry.GetCachedAsset(); 187 | } 188 | 189 | /// 190 | /// Called to clean up and unload assets that have no remaining references 191 | /// 192 | public void ClearUnusedAssets() 193 | { 194 | //Remove Unused entries 195 | var unusedEntries = CacheDictionary.Where((pair) => (pair.Value.RefCount <= 0)).ToList(); 196 | foreach (var pair in unusedEntries) 197 | { 198 | CacheDictionary.Remove(pair.Key); 199 | pair.Value.Dispose(); 200 | } 201 | } 202 | 203 | } 204 | } 205 | -------------------------------------------------------------------------------- /Runtime/AssetCache.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 0507219ca4a9342c69ae868e09587bd0 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/IAssetLoader.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Gameframe.AssetCache 4 | { 5 | /// 6 | /// Interface for loading and unloading assets in AssetCache 7 | /// 8 | /// UnityEngine.Object asset type 9 | public interface IAssetLoader : IKeyedAssetLoader where TAssetType : class 10 | { 11 | } 12 | 13 | /// 14 | /// Interface for loading and unloading assets in AssetCache 15 | /// 16 | /// UnityEngine.Object asset type 17 | public interface IKeyedAssetLoader where TAssetType : class 18 | { 19 | /// 20 | /// Loads an asset asynchronously 21 | /// 22 | /// path to the asset to be loaded 23 | /// Task that returns the asset type 24 | Task LoadAsync(TKeyType assetKey); 25 | 26 | /// 27 | /// Unloads an asset 28 | /// 29 | /// Asset to be unloaded 30 | void Unload(TAssetType asset); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Runtime/IAssetLoader.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f6016778172524502a3faeb0143864ef 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/RawImageWebAssetCache.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using UnityEngine.UI; 3 | 4 | namespace Gameframe.AssetCache 5 | { 6 | /// 7 | /// Uses an internal static WebTextureCache to load a texture from the web and cache it 8 | /// 9 | public class RawImageWebAssetCache : MonoBehaviour 10 | { 11 | public RawImage image; 12 | public string url; 13 | public bool cleanCacheOnDisable = true; 14 | 15 | private static readonly WebTextureCache Cache = new WebTextureCache(); 16 | 17 | private WebTextureCache.ICachedAsset cachedAsset; 18 | 19 | private void OnEnable() 20 | { 21 | image.enabled = false; 22 | Load(); 23 | } 24 | 25 | private void OnDisable() 26 | { 27 | Unload(); 28 | if (cleanCacheOnDisable) 29 | { 30 | Clean(); 31 | } 32 | } 33 | 34 | private async void Load() 35 | { 36 | if (string.IsNullOrEmpty(url)) 37 | { 38 | return; 39 | } 40 | 41 | var task = Cache.GetAsync(url); 42 | await task; 43 | 44 | if (!enabled || !gameObject.activeInHierarchy) 45 | { 46 | task.Result.Dispose(); 47 | return; 48 | } 49 | 50 | if (cachedAsset != null) 51 | { 52 | Unload(); 53 | } 54 | 55 | cachedAsset = task.Result; 56 | 57 | image.texture = cachedAsset.Asset; 58 | image.enabled = true; 59 | } 60 | 61 | 62 | private void Unload() 63 | { 64 | if (cachedAsset == null) 65 | { 66 | return; 67 | } 68 | 69 | cachedAsset.Dispose(); 70 | cachedAsset = null; 71 | } 72 | 73 | public static void Clean() 74 | { 75 | Cache.ClearUnusedAssets(); 76 | } 77 | 78 | private void OnValidate() 79 | { 80 | if (image == null) 81 | { 82 | image = GetComponent(); 83 | } 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /Runtime/RawImageWebAssetCache.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 44605c37ff5fe4d3cbfda39d9b9f525e 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/WebTextureCache.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using System.Threading.Tasks; 4 | using UnityEngine; 5 | using UnityEngine.Networking; 6 | 7 | namespace Gameframe.AssetCache 8 | { 9 | internal class WebTextureLoader : IAssetLoader 10 | { 11 | public async Task LoadAsync(string assetPath) 12 | { 13 | using (var request = UnityWebRequestTexture.GetTexture(assetPath)) 14 | { 15 | var asyncOp = request.SendWebRequest(); 16 | 17 | while (!asyncOp.isDone) 18 | { 19 | await Task.Yield(); 20 | } 21 | 22 | if (request.isNetworkError) 23 | { 24 | throw new Exception($"Network Error: {request.error}"); 25 | } 26 | 27 | if (request.isHttpError) 28 | { 29 | throw new HttpRequestException(request.error); 30 | } 31 | 32 | return DownloadHandlerTexture.GetContent(request); 33 | } 34 | } 35 | 36 | public void Unload(Texture2D asset) 37 | { 38 | UnityEngine.Object.Destroy(asset); 39 | } 40 | } 41 | 42 | /// 43 | /// Cache for loading textures from Web URLs 44 | /// 45 | public class WebTextureCache : AssetCache 46 | { 47 | public WebTextureCache() : base(new WebTextureLoader()) { } 48 | } 49 | } -------------------------------------------------------------------------------- /Runtime/WebTextureCache.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 61187da647b4941349d1163e3903d84d 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Runtime/com.gameframe.assetcache.asmdef: -------------------------------------------------------------------------------- 1 | { "name": "com.gameframe.assetcache" } -------------------------------------------------------------------------------- /Runtime/com.gameframe.assetcache.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 32f63ae826e674d19b4c67f92cfdebe3 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Tests.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 17b082868ea0a4fdf937635e86e509b1 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Tests/Editor.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e8e6bb29d8684480ebed8a5116222b32 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Tests/Editor/AssetCacheEditorTests.cs: -------------------------------------------------------------------------------- 1 | namespace Gameframe.AssetCache.Tests.Editor 2 | { 3 | public class AssetCacheEditorTests 4 | { 5 | } 6 | } 7 | 8 | 9 | -------------------------------------------------------------------------------- /Tests/Editor/AssetCacheEditorTests.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e03a60480d2ea4027b00e7e2fd35c28f 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Tests/Editor/com.gameframe.assetcache.Editor.Tests.asmdef: -------------------------------------------------------------------------------- 1 | { "name": "com.gameframe.assetcache.Editor.Tests", "references": [ "com.gameframe.assetcache" ], "optionalUnityReferences": ["TestAssemblies"], "includePlatforms": [ "Editor" ], "excludePlatforms": [] } -------------------------------------------------------------------------------- /Tests/Editor/com.gameframe.assetcache.Editor.Tests.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 72e679633458647279159eab454e6ab1 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Tests/Runtime.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 03f3d7b9ec5cf4d75aa28fb268b9fcd8 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Tests/Runtime/AssetCacheTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Threading.Tasks; 4 | using NUnit.Framework; 5 | using UnityEngine; 6 | using UnityEngine.TestTools; 7 | 8 | namespace Gameframe.AssetCache.Tests 9 | { 10 | public class AssetCacheTests 11 | { 12 | private class TestTextureLoader : IAssetLoader 13 | { 14 | public Task LoadAsync(string s) 15 | { 16 | Texture2D tex = new Texture2D(32, 32); 17 | return Task.Run(() => 18 | { 19 | Task.Delay(100); 20 | return tex; 21 | }); 22 | } 23 | 24 | public void Unload(Texture2D asset) 25 | { 26 | UnityEngine.Object.Destroy(asset); 27 | } 28 | } 29 | 30 | private AssetCache CreateCache() 31 | { 32 | var cache = new AssetCache(new TestTextureLoader()); 33 | return cache; 34 | } 35 | 36 | [Test] 37 | public void CreateAsssetCache() 38 | { 39 | var cache = CreateCache(); 40 | Assert.IsTrue(cache != null); 41 | } 42 | 43 | [UnityTest] 44 | public IEnumerator GetAsset() 45 | { 46 | var cache = CreateCache(); 47 | var cachedAssetTask = cache.GetAsync("txone"); 48 | 49 | while (!cachedAssetTask.IsCompleted) 50 | { 51 | yield return null; 52 | } 53 | 54 | var cachedAsset = cachedAssetTask.Result; 55 | 56 | Assert.IsTrue(cachedAsset.Asset != null); 57 | Assert.IsTrue(cachedAsset.RefCount == 1); 58 | } 59 | 60 | [UnityTest] 61 | public IEnumerator DisposeDecrementsRefCount() 62 | { 63 | var cache = CreateCache(); 64 | var cachedAssetTask = cache.GetAsync("txone"); 65 | 66 | while (!cachedAssetTask.IsCompleted) 67 | { 68 | yield return null; 69 | } 70 | 71 | var cachedAsset = cachedAssetTask.Result; 72 | Assert.IsTrue(cachedAsset.Asset != null); 73 | Assert.IsTrue(cachedAsset.RefCount == 1); 74 | 75 | cachedAsset.Dispose(); 76 | 77 | Assert.IsTrue(cachedAsset.RefCount == 0); 78 | } 79 | 80 | [UnityTest] 81 | public IEnumerator GetAssetTwice() 82 | { 83 | var cache = CreateCache(); 84 | var url = "txone"; 85 | var cachedAssetTask = cache.GetAsync(url); 86 | 87 | while (!cachedAssetTask.IsCompleted) 88 | { 89 | yield return null; 90 | } 91 | 92 | var cachedAsset1 = cachedAssetTask.Result; 93 | Assert.IsTrue(cachedAsset1.Asset != null); 94 | Assert.IsTrue(cachedAsset1.RefCount == 1); 95 | 96 | cachedAssetTask = cache.GetAsync(url); 97 | 98 | while (!cachedAssetTask.IsCompleted) 99 | { 100 | yield return null; 101 | } 102 | 103 | var cachedAsset2 = cachedAssetTask.Result; 104 | //Confirm that the two cached assets refer to the same thing but are themselves different 105 | Assert.IsTrue(cachedAsset1 != cachedAsset2); 106 | Assert.IsTrue(cachedAsset2.Asset == cachedAsset1.Asset); 107 | Assert.IsTrue(cachedAsset1.RefCount == 2); 108 | Assert.IsTrue(cachedAsset2.RefCount == 2); 109 | 110 | } 111 | 112 | [UnityTest] 113 | public IEnumerator ExceptionOnDisposeTwice() 114 | { 115 | var cache = CreateCache(); 116 | var url = "txone"; 117 | var cachedAssetTask = cache.GetAsync(url); 118 | 119 | while (!cachedAssetTask.IsCompleted) 120 | { 121 | yield return null; 122 | } 123 | 124 | var cachedAsset = cachedAssetTask.Result; 125 | var copiedReference = cachedAsset; 126 | 127 | Assert.IsTrue(cachedAsset.Asset != null); 128 | Assert.IsTrue(cachedAsset.RefCount == 1); 129 | 130 | cachedAsset.Dispose(); 131 | Assert.IsTrue(cachedAsset.RefCount == 0); 132 | 133 | Assert.Throws(() => 134 | { 135 | copiedReference.Dispose(); 136 | }); 137 | } 138 | 139 | [UnityTest] 140 | public IEnumerator CanClone() 141 | { 142 | var cache = CreateCache(); 143 | var url = "txone"; 144 | var cachedAssetTask = cache.GetAsync(url); 145 | 146 | while (!cachedAssetTask.IsCompleted) 147 | { 148 | yield return null; 149 | } 150 | 151 | var cachedAsset = cachedAssetTask.Result; 152 | var copiedReference = cachedAsset.Clone(); 153 | 154 | Assert.IsTrue(cachedAsset.Asset != null); 155 | Assert.IsTrue(cachedAsset.RefCount == 2); 156 | 157 | cachedAsset.Dispose(); 158 | Assert.IsTrue(cachedAsset.RefCount == 1); 159 | 160 | copiedReference.Dispose(); 161 | Assert.IsTrue(cachedAsset.RefCount == 0); 162 | } 163 | 164 | [UnityTest] 165 | public IEnumerator CanClean() 166 | { 167 | var cache = CreateCache(); 168 | 169 | var url = "txone"; 170 | var cachedAssetTask = cache.GetAsync(url); 171 | 172 | while (!cachedAssetTask.IsCompleted) 173 | { 174 | yield return null; 175 | } 176 | 177 | var cachedAsset = cachedAssetTask.Result; 178 | var copiedReference = cachedAsset.Clone(); 179 | 180 | var asset = cachedAsset.Asset; 181 | 182 | Assert.IsTrue(cachedAsset.Asset != null); 183 | Assert.IsTrue(cachedAsset.RefCount == 2); 184 | 185 | cachedAsset.Dispose(); 186 | Assert.IsTrue(cachedAsset.RefCount == 1); 187 | 188 | cache.ClearUnusedAssets(); 189 | 190 | //Ensure cached asset was not destroyed yet 191 | Assert.IsFalse(asset == null); 192 | 193 | //Ensure cached asset gets destroyed once ref count hits 0 194 | copiedReference.Dispose(); 195 | Assert.IsTrue(cachedAsset.RefCount == 0); 196 | cache.ClearUnusedAssets(); 197 | 198 | //Must wait a frame after the unload/destroy for asset reference null check to return true 199 | yield return null; 200 | Assert.IsTrue(asset == null); 201 | } 202 | 203 | } 204 | 205 | } 206 | -------------------------------------------------------------------------------- /Tests/Runtime/AssetCacheTests.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: bb632a5131e884f7b8f7b2764d6e9e1a 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Tests/Runtime/com.gameframe.assetcache.Tests.asmdef: -------------------------------------------------------------------------------- 1 | { "name": "com.gameframe.assetcache.Tests", "references": [ "com.gameframe.assetcache" ], "optionalUnityReferences": ["TestAssemblies"], "includePlatforms": [], "excludePlatforms": [] } -------------------------------------------------------------------------------- /Tests/Runtime/com.gameframe.assetcache.Tests.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 044aa3a09dc784d2bb2cc771a6bb7fb1 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "com.gameframe.assetcache", 3 | "displayName": "Gameframe.AssetCache", 4 | "version": "1.3.0", 5 | "description": "Library for caching and unloading assets", 6 | "keywords": [], 7 | "author": { 8 | "name": "Cory Leach", 9 | "email": "cory.leach@gmail.com", 10 | "url": "https://coryleach.info", 11 | "github": "coryleach", 12 | "twitter": "coryleach", 13 | "kofi": "https://ko-fi.com/coryleach" 14 | }, 15 | "type": "library", 16 | "repositoryName": "UnityAssetCache" 17 | } -------------------------------------------------------------------------------- /package.json.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e887c8cc24acc4eeeb61e0def227e2f0 3 | PackageManifestImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | --------------------------------------------------------------------------------