ResourcesComponent.cs 3.2 KB
Newer Older
1 2
using System;
using System.Collections.Generic;
3
using System.Threading.Tasks;
4 5 6 7
using UnityEngine;

namespace Model
{
8
	[EntityEvent(EntityEventId.ResourcesComponent)]
9 10 11 12 13 14 15
	public class ResourcesComponent: Component
	{
		public static AssetBundleManifest AssetBundleManifestObject { get; set; }

		private readonly Dictionary<string, UnityEngine.Object> resourceCache = new Dictionary<string, UnityEngine.Object>();

		private readonly Dictionary<string, AssetBundle> bundleCaches = new Dictionary<string, AssetBundle>();
16
		
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
		public K GetReference<K>(string bundle, string prefab, string key) where K : class
		{
			GameObject gameObject = this.GetAsset<GameObject>(bundle, prefab);
			return gameObject.GetComponent<ReferenceCollector>().Get<K>(key);
		}

		public K GetAsset<K>(string bundleName, string prefab) where K : class
		{
			string path = $"{bundleName}.unity3d/{prefab}".ToLower();

			UnityEngine.Object resource = null;
			if (this.resourceCache.TryGetValue(path, out resource))
			{
				return resource as K;
			}
32
			
33 34 35 36 37 38 39
			if (Define.LoadResourceType == LoadResourceType.Async)
			{
				if (!this.bundleCaches.ContainsKey($"{bundleName}.unity3d".ToLower()))
				{
					return null;
				}

40
				throw new Exception($"异步加载资源,资源不在resourceCache中: {bundleName} {path}");
41 42 43 44
			}

			try
			{
45
				resource = ResourceHelper.LoadResource(bundleName, prefab);
46 47 48 49
				this.resourceCache.Add(path, resource);
			}
			catch (Exception e)
			{
50
				throw new Exception($"加载资源出错,输入路径:{path}", e);
51 52 53 54 55
			}

			return resource as K;
		}

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
		public async Task DownloadAndCacheAsync(string uri, string assetBundleName)
		{
			assetBundleName = (assetBundleName + ".unity3d").ToLower();

			AssetBundle assetBundle;
			// 异步下载资源
			string url = uri + "StreamingAssets/" + assetBundleName;
			int count = 0;
			while (true)
			{
				try
				{
					++count;
					if (count > 1)
					{
						await Game.Scene.GetComponent<TimerComponent>().WaitAsync(2000);
					}

					if (this.Id == 0)
					{
						return;
					}

					using (WWWAsync wwwAsync = new WWWAsync())
					{
						await wwwAsync.LoadFromCacheOrDownload(url, ResourcesComponent.AssetBundleManifestObject.GetAssetBundleHash(assetBundleName));
						assetBundle = wwwAsync.www.assetBundle;
					}
					break;
				}
				catch (Exception e)
				{
					Log.Error(e.ToString());
				}
			}

			if (!assetBundle.isStreamedSceneAssetBundle)
			{
				// 异步load资源到内存cache住
				UnityEngine.Object[] assets;
				using (AssetBundleLoaderAsync assetBundleLoaderAsync = new AssetBundleLoaderAsync(assetBundle))
				{
					assets = await assetBundleLoaderAsync.LoadAllAssetsAsync();
				}

				foreach (UnityEngine.Object asset in assets)
				{
					string path = $"{assetBundleName}/{asset.name}".ToLower();
					this.resourceCache[path] = asset;
				}
			}

			if (this.bundleCaches.ContainsKey(assetBundleName))
			{
110
				throw new Exception($"重复加载资源: {assetBundleName}");
111 112 113 114
			}
			this.bundleCaches[assetBundleName] = assetBundle;
		}

T
tanghai 已提交
115 116 117 118 119 120
		public override void Dispose()
		{
			if (this.Id == 0)
			{
				return;
			}
121

T
tanghai 已提交
122
			base.Dispose();
123

T
tanghai 已提交
124 125 126
			foreach (var assetBundle in bundleCaches)
			{
				assetBundle.Value?.Unload(true);
127
			}
T
tanghai 已提交
128
		}
129 130
	}
}