private IEnumerator LoadAssetBundleFromFile(string assetBundleName) { if (m_loadedAssetBundles.ContainsKey(assetBundleName)) { yield break; } string url = m_loadFromFileURL + assetBundleName; AssetBundleCreateRequest assetBundleCreateRequest = UnityEngine.AssetBundle.LoadFromFileAsync(url); yield return(assetBundleCreateRequest); if (assetBundleCreateRequest.assetBundle == null) { JSLDebug.LogErrorFormat("[AssetBundleManager] - Failed to load AssetBundle from {0}", url); yield break; } #if UNITY_EDITOR ReassignShader(assetBundleCreateRequest.assetBundle); #endif var loadedAssetBundle = new LoadedAssetBundle(assetBundleCreateRequest.assetBundle); m_loadedAssetBundles[assetBundleName] = loadedAssetBundle; }
public void RegisterListener(int eventId, IEventListener listener, int priority = 0) { if (!m_eventListenerContainers.ContainsKey(eventId)) { m_eventListenerContainers[eventId] = new List <ListenerContainer>(); } List <ListenerContainer> listeners = m_eventListenerContainers[eventId]; int listenerCount = listeners.Count; for (int i = 0; i < listenerCount; i++) { if (listeners[i].Listener == listener) { JSLDebug.LogException(new Exception("[EventManager] - Listener is already registered for this object.")); return; } } listeners.Add(new ListenerContainer(listener, priority)); listeners.Sort(); m_eventListenerContainers[eventId] = listeners; if (m_eventListenerArrays.ContainsKey(eventId)) { m_eventListenerArrays[eventId] = listeners.ToArray(); } else { m_eventListenerArrays.Add(eventId, listeners.ToArray()); } }
private IEnumerator PreInitialize(string relativePath) { string platformName = AssetBundleDef.GetPlatformName(); m_downloadingURL = string.Format("{0}/{1}/", relativePath, platformName); JSLDebug.LogFormat("[AssetBundleManager] - The AssetBundle Download URL is {0}", m_downloadingURL); m_loadFromFileURL = string.Format("{0}/{1}/", AssetBundleDef.GetStreamingAssetsPath(), platformName); JSLDebug.LogFormat("[AssetBundleManager] - The AssetBundle LoadFromFile URL is {0}", m_loadFromFileURL); yield return(StartCoroutine(LoadCatalogFromNetwork())); if (m_assetBundleCatalogs == null) { if (m_onInitializeFinish != null) { m_onInitializeFinish(false); m_onInitializeFinish = null; yield break; } } AssetBundleLoadManifestRequest assetBundleLoadManifestRequest = InitializeManifest(platformName); if (assetBundleLoadManifestRequest != null) { yield return(assetBundleLoadManifestRequest); } }
private IEnumerator LoadCatalogFromNetwork() { JSLDebug.LogFormat("[AssetBundleManager] - Start download AssetBundleCatalog at frame {0}", Time.frameCount); UnityWebRequest request = UnityWebRequest.Get(m_downloadingURL + AssetBundleDef.CATALOG_FILE_NAME); request.SendWebRequest(); while (!request.isDone) { yield return(null); } if (!string.IsNullOrEmpty(request.error)) { m_assetBundleCatalogs = null; JSLDebug.LogErrorFormat("[AssetBundleManager] - Download AssetBundleCatalog failed. Error log \"{0}\"", request.error); } else { m_assetBundleCatalogs = new AssetBundleCatalogs(request.downloadHandler.text); JSLDebug.LogFormat("[AssetBundleManager] - Download AssetBundleCatalog complete at frame {0}", Time.frameCount); } request.Dispose(); }
public void Initialize(AssetBundleInitializeData initializeData) { m_maxDownloadRequest = initializeData.maxDownloadRequestAmount; m_onInitializeFinish = initializeData.onInitializeFinish; m_assetBundleLoadType = initializeData.assetBundleLoadType; JSLDebug.LogFormat("[AssetBundleManager] - Initialize with load type '{0}'", m_assetBundleLoadType); if (m_assetBundleLoadType == AssetBundleLoadType.Streaming) { initializeData.downloadURL = AssetBundleDef.GetDownloadStreamingAssetsPath(); } if (m_assetBundleLoadType != AssetBundleLoadType.Simulate) { StartCoroutine(PreInitialize(initializeData.downloadURL)); } else { if (m_onInitializeFinish != null) { m_onInitializeFinish(true); m_onInitializeFinish = null; } } }
private void UpdateCompleteDownloadRequests() { foreach (string key in m_completeDownloadAssetBundles) { JSLDebug.LogFormat("[AssetBundleManager] - Download asset bundle '{0}' successfully at frame {1}", key, Time.frameCount); m_cacheRequest = m_downloadingRequests[key]; m_cacheRequest.Dispose(); m_downloadingRequests.Remove(key); } if (m_assetBundleDownloadProgress != null) { m_assetBundleDownloadProgress.SetDownloadCount(m_downloadingRequests.Count + m_waitingDownloadRequests.Count); if (m_assetBundleDownloadProgress.progress == 1) { JSLDebug.LogFormat("[AssetBundleManager] - Download AssetBundle complete at frame {0}", Time.frameCount); ResourceManager.Instance.Clear(); } if (m_onAssetBundleDownloadProgressChanged != null) { m_onAssetBundleDownloadProgressChanged(m_assetBundleDownloadProgress); } } if (m_downloadingRequests.Count == 0 && m_waitingDownloadRequests.Count == 0) { m_onAssetBundleDownloadProgressChanged = null; m_assetBundleDownloadProgress = null; } m_inProgressRequests.RemoveAll(request => !request.Update()); }
private IEnumerator PreloadAllAssetBundleAsync <T>(string cacheKey, string assetBundleName, string assetName) where T : UnityEngine.Object { int startFrameCount = Time.frameCount; AssetBundleLoadAllAssetRequest <T> request = AssetBundleManager.Instance.LoadAllAssetAsync <T>(assetBundleName, assetName); if (null == request) { yield break; } yield return(request); T[] assets = request.GetAsset(); if (null == assets || assets.Length == 0) { yield break; } LoadedResource res = new LoadedResource(assets); m_loadedResources[cacheKey] = res; JSLDebug.LogFormat(LOG_LOADALL_ASSET_SUCCEED, assetName, startFrameCount, Time.frameCount); }
private static void InitializeDefaultPool(string key, T reference, int initialSize) { if (m_defaultPool == null) { m_defaultPool = new Pool <T>(key, reference, initialSize); JSLDebug.LogFormat("[PoolCollections] - There is no default pool for type '{0}', create a new one with initial size '{1}'.", typeof(T).Name, initialSize); } }
public override bool IsDone() { if (null == m_request && null != m_downloadingError) { JSLDebug.LogError(m_downloadingError); return(true); } return(null != m_request && m_request.isDone); }
public override bool IsDone() { if (null == m_request && null != m_downloadingError) { JSLDebug.LogErrorFormat("[AssetBundleLoadAssetRequestFull] - Load AssetBundle '{0}' failed with reason {1}", m_assetBundleName, m_downloadingError); return(true); } return(null != m_request && m_request.isDone); }
private static void ClearCache() { if (Caching.ClearCache()) { JSLDebug.Log("Cleaned all caches successfully."); } else { JSLDebug.LogWarning("Failed to clean caches."); } }
public override bool Update() { base.Update(); if (null != m_request && m_request.isDone) { JSLDebug.LogFormat("[AssetBundleLoadManifestRequest] - Setup AssetBundleManifest successfully at frame {0}", Time.frameCount); AssetBundleManager.Instance.SetupManifest(GetAsset()); return(false); } return(true); }
private static void InitializePools(string key, T reference, int initialSize) { if (m_pools == null) { m_pools = new Dictionary <string, Pool <T> >(); } if (!m_pools.ContainsKey(key)) { m_pools.Add(key, new Pool <T>(key, reference, initialSize)); JSLDebug.LogFormat("[PoolCollections] - There is no pool for type '{0}' of key '{1}', create a new one with initial size '{2}'.", typeof(T).Name, key, initialSize); } }
protected void Spawn(int spawnSize) { if (m_pool.Count >= spawnSize) { JSLDebug.Log("[Pool] - The pool size is bigger than the spawn size, don't need to create new object."); return; } for (int i = 0; i < spawnSize; i++) { Create(); } }
private IEnumerator PreloadSceneAsync(string sceneName, LoadSceneMode loadSceneMode, Action <float> progressCallback) { int startFrameCount = Time.frameCount; m_cacheAsyncOperation = SceneManager.LoadSceneAsync(sceneName, loadSceneMode); while (!m_cacheAsyncOperation.isDone) { progressCallback?.Invoke(m_cacheAsyncOperation.progress); yield return(null); } progressCallback?.Invoke(1f); JSLDebug.LogFormat(LOG_LOAD_SCENE_SUCCEED, sceneName, startFrameCount, Time.frameCount); }
private IEnumerator StartLoadAsync <T>(string assetBundleName, string assetName, Action <T, object> callback, object customData, bool unloadAutomatically) where T : UnityEngine.Object { if (string.IsNullOrEmpty(assetName)) { JSLDebug.LogErrorFormat(LOG_LOAD_ASSET_FAILED, assetName, assetBundleName); callback?.Invoke(null, customData); yield break; } string cacheKey = GetCacheKey <T>(assetBundleName, assetName); if (IsPrefab <T>()) { yield return(PreloadAsync <GameObject>(cacheKey, assetBundleName, assetName)); } else { yield return(PreloadAsync <T>(cacheKey, assetBundleName, assetName)); } if (!InCache(cacheKey)) { JSLDebug.LogErrorFormat(LOG_LOAD_ASSET_FAILED, assetName, assetBundleName); callback?.Invoke(null, customData); RemoveAsyncLoadingReferencedCounts(cacheKey); yield break; } LoadedResource res = m_loadedResources[cacheKey]; res.referencedCount++; T asset = res.resource as T; if (asset == null) { asset = (res.resource as GameObject).GetComponent <T>(); } callback?.Invoke(asset, customData); RemoveAsyncLoadingReferencedCounts(cacheKey); if (unloadAutomatically) { Unload <T>(assetBundleName, assetName); } }
private IEnumerator StartUnloadSceneAsync(string sceneName, Action <object> callback, object customData) { int startFrameCount = Time.frameCount; if (SceneManager.GetActiveScene().name == sceneName) { JSLDebug.LogWarning(LOG_UNLOAD_ACTIVE_SCENE); callback?.Invoke(customData); yield break; } m_shouldUnload = false; for (int i = 0; i < SceneManager.sceneCount; i++) { if (SceneManager.GetSceneAt(i).name == sceneName) { m_shouldUnload = true; } } if (!m_shouldUnload) { JSLDebug.LogWarning(LOG_NO_SCENE_TO_UNLOAD); callback?.Invoke(customData); yield break; } m_cacheAsyncOperation = SceneManager.UnloadSceneAsync(sceneName); if (m_cacheAsyncOperation == null) { callback?.Invoke(customData); yield break; } while (!m_cacheAsyncOperation.isDone) { yield return(0); } JSLDebug.LogFormat(LOG_UNLOAD_SCENE_SUCCEED, sceneName, startFrameCount, Time.frameCount); callback?.Invoke(customData); }
public static void Build(AssetBundleBuildInfo buildInfo) { AssetBundleNameBuilder.Build(); AssetDatabase.Refresh(); AssetDatabase.RemoveUnusedAssetBundleNames(); if (buildInfo.cleanFolders) { if (Directory.Exists(buildInfo.outputPath)) { Directory.Delete(buildInfo.outputPath, true); } } if (!Directory.Exists(buildInfo.outputPath)) { Directory.CreateDirectory(buildInfo.outputPath); } if (buildInfo.specificAssetBundles == null || buildInfo.specificAssetBundles.Length == 0) { BuildPipeline.BuildAssetBundles(buildInfo.outputPath, buildInfo.buildAssetBundleOptions, buildInfo.buildTarget); } else { BuildPipeline.BuildAssetBundles(buildInfo.outputPath, buildInfo.specificAssetBundles, buildInfo.buildAssetBundleOptions, buildInfo.buildTarget); } AssetBundleCatalogBuilder.Build(buildInfo.outputPath); if (buildInfo.copyToStreamingAssets) { string streamingAssetsPath = Path.Combine(Application.streamingAssetsPath, AssetBundleDef.ASSET_BUNDLE_OUTPUT_FOLDER); streamingAssetsPath = Path.Combine(streamingAssetsPath, AssetBundleDef.GetPlatformName()); if (Directory.Exists(streamingAssetsPath)) { Directory.Delete(streamingAssetsPath, true); } DirectoryCopy(buildInfo.outputPath, streamingAssetsPath); } AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); JSLDebug.Log("Build AssetBundles successfully."); }
private AssetBundleLoadManifestRequest InitializeManifest(string path) { UnloadAssetBundles(new List <string> { AssetBundleDef.GetPlatformName() }); JSLDebug.LogFormat("[AssetBundleManager] - Start download AssetBundleManifest at frame {0}", Time.frameCount); DownloadAssetBundle(path, true); AssetBundleLoadManifestRequest assetBundleLoadManifestRequest = new AssetBundleLoadManifestRequest(path, "AssetBundleManifest"); m_inProgressRequests.Add(assetBundleLoadManifestRequest); return(assetBundleLoadManifestRequest); }
private IEnumerator PreloadAllResourceAsync <T>(string cacheKey, string assetName) where T : UnityEngine.Object { int startFrameCount = Time.frameCount; T[] assets = Resources.LoadAll <T>(assetName); LoadedResource res = new LoadedResource(assets); if (null == res.resources || res.resources.Length == 0) { yield break; } m_loadedResources[cacheKey] = res; JSLDebug.LogFormat(LOG_LOADALL_ASSET_SUCCEED, assetName, startFrameCount, Time.frameCount); }
private IEnumerator PreloadSceneAssetBundleAsync(string assetBundleName, string sceneName, LoadSceneMode loadSceneMode, Action <float> progressCallback) { int startFrameCount = Time.frameCount; m_cacheAssetBundleLoadRequest = AssetBundleManager.Instance.LoadSceneAsync(assetBundleName, sceneName, loadSceneMode); if (null == m_cacheAssetBundleLoadRequest) { yield break; } while (!m_cacheAssetBundleLoadRequest.IsDone()) { progressCallback?.Invoke(m_cacheAssetBundleLoadRequest.GetProgress()); yield return(null); } progressCallback?.Invoke(m_cacheAssetBundleLoadRequest.GetProgress()); JSLDebug.LogFormat(LOG_LOAD_SCENE_SUCCEED, sceneName, startFrameCount, Time.frameCount); }
private static void SetAssetBundleName(DirectoryInfo directoryInfo, FileInfo fileInfo) { string assetBundleFolderPath = Application.dataPath + "/" + ASSET_BUNDLE_RESOURCE_FOLDER; assetBundleFolderPath = assetBundleFolderPath.Replace("/", "\\"); string assetbundleName = directoryInfo.FullName; assetbundleName = assetbundleName.Replace(assetBundleFolderPath, ""); assetbundleName = Path.Combine(assetbundleName, fileInfo.Name.Replace(fileInfo.Extension, "")); assetbundleName = assetbundleName.ToLower(); string filePath = fileInfo.FullName; filePath = filePath.Replace(Application.dataPath.Replace("/", "\\"), ""); filePath = "Assets" + filePath; JSLDebug.Log(filePath); AssetImporter.GetAtPath(filePath).assetBundleName = assetbundleName; }
public void Download(Action <AssetBundleDownloadProgress> onAssetBundleDownloadProgressChanged) { m_onAssetBundleDownloadProgressChanged = onAssetBundleDownloadProgressChanged; if (m_assetBundleLoadType == AssetBundleLoadType.Simulate) { JSLDebug.LogFormat("[AssetBundleManager] - The AssetBundle load type is on Simulate, don't need to download."); return; } if (null == m_assetBundleManifest) { JSLDebug.LogError("[AssetBundleManager] - Please download AssetBundleManifest by calling ResourceSystem.InstancenitAssetBundle() first"); return; } JSLDebug.LogFormat("[AssetBundleManager] - Start download AssetBundle at frame {0}", Time.frameCount); string[] allAssetBundles = m_assetBundleManifest.GetAllAssetBundles(); List <string> downloadAssetBundleNames = new List <string>(); for (int i = 0; i < allAssetBundles.Length; i++) { if (Caching.IsVersionCached(m_downloadingURL + allAssetBundles[i], m_assetBundleManifest.GetAssetBundleHash(allAssetBundles[i]))) { continue; } downloadAssetBundleNames.Add(allAssetBundles[i]); } UnloadAssetBundles(allAssetBundles.ToList()); for (int i = 0; i < allAssetBundles.Length; i++) { DownloadAssetBundle(allAssetBundles[i], false); } m_assetBundleDownloadProgress = new AssetBundleDownloadProgress(allAssetBundles.Length, m_assetBundleCatalogs.GetAllFileSize(downloadAssetBundleNames)); }
private IEnumerator StartLoadAllAsync <T>(string assetBundleName, string assetName, Action <List <T>, object> callback, object customData, bool unloadAutomatically) where T : UnityEngine.Object { string cacheKey = GetCacheKey <T>(assetBundleName, assetName); yield return(PreloadAllAsync <T>(cacheKey, assetBundleName, assetName)); if (!InCache(cacheKey)) { JSLDebug.LogWarningFormat(LOG_LOADALL_ASSET_FAILED, assetName, assetBundleName); callback?.Invoke(null, customData); RemoveAsyncLoadingReferencedCounts(cacheKey); yield break; } LoadedResource res = m_loadedResources[cacheKey]; res.referencedCount++; List <T> assets = new List <T>(); T cache = null; for (int i = 0; i < res.resources.Length; i++) { cache = (T)res.resources[i]; if (cache) { assets.Add(cache); } } callback?.Invoke(assets, customData); RemoveAsyncLoadingReferencedCounts(cacheKey); if (unloadAutomatically) { Unload <T>(assetBundleName, assetName); } }
private IEnumerator PreloadResourceAsync <T>(string cacheKey, string assetName) where T : UnityEngine.Object { int startFrameCount = Time.frameCount; ResourceRequest resourceRequest = Resources.LoadAsync <T>(assetName); while (!resourceRequest.isDone) { yield return(0); } LoadedResource res = new LoadedResource(resourceRequest.asset); if (null == res.resource) { yield break; } m_loadedResources[cacheKey] = res; JSLDebug.LogFormat(LOG_LOAD_ASSET_SUCCEED, assetName, startFrameCount, Time.frameCount); }
public static void CleanupMissingScriptsInTheActiveScene() { GameObject[] rootGameObjects = EditorSceneManager.GetActiveScene().GetRootGameObjects(); if (rootGameObjects == null || rootGameObjects.Length == 0) { JSLDebug.Log("[ComponentUtils] - There is no gameObjects."); return; } Object[] result = EditorUtility.CollectDeepHierarchy(rootGameObjects); int count = 0; foreach (Object obj in result) { count++; if (obj == null) { continue; } if (EditorUtility.DisplayCancelableProgressBar("Hold on...", string.Format("Cleanup Missing Scripts in object '{0}'...{1}/{2}", obj.name, count, result.Length), (float)count / result.Length)) { break; } if (obj is GameObject gameObject) { RemoveMissingScript(gameObject); } } EditorUtility.ClearProgressBar(); EditorSceneManager.SaveOpenScenes(); }
private static void RemoveMissingScript(GameObject gameObject) { Component[] components = gameObject.GetComponents <Component>(); if (components == null || components.Length == 0) { return; } SerializedObject serializedObject = new SerializedObject(gameObject); SerializedProperty serializedProperty = serializedObject.FindProperty("m_Component"); for (int i = components.Length - 1; i >= 0; i--) { if (components[i] == null) { JSLDebug.LogFormat("There is missing component in gameObject '{0}', destroy it.", gameObject.name); serializedProperty.DeleteArrayElementAtIndex(i); EditorSceneManager.MarkAllScenesDirty(); } } serializedObject.ApplyModifiedProperties(); }
private void UpdateWaitingDownloadRequests() { if (m_waitingDownloadRequests.Count == 0 || m_downloadingRequests.Count() >= m_maxDownloadRequest) { return; } for (int i = m_downloadingRequests.Count(); i < m_maxDownloadRequest; i++) { if (m_waitingDownloadRequests.Count == 0) { break; } WaitingDownloadRequest waitingDownloadRequest = m_waitingDownloadRequests.Dequeue(); UnityWebRequest request = null; string url = m_downloadingURL + waitingDownloadRequest.AssetBundleName; if (waitingDownloadRequest.IsManifest) { request = UnityWebRequestAssetBundle.GetAssetBundle(url); } else { JSLDebug.LogFormat("[AssetBundleManager] - Start downloading asset bundle '{0}' at frame {1}", waitingDownloadRequest.AssetBundleName, Time.frameCount); request = UnityWebRequestAssetBundle.GetAssetBundle(url, m_assetBundleManifest.GetAssetBundleHash(waitingDownloadRequest.AssetBundleName), 0); } request.SendWebRequest(); m_downloadingRequests.Add(waitingDownloadRequest.AssetBundleName, request); m_waitingDownloadAssetBundleNames.Remove(waitingDownloadRequest.AssetBundleName); } }
public static void Build(string outputPath) { string[] allAssetBundleNames = AssetDatabase.GetAllAssetBundleNames(); string fullPath; Hash128 hash128; uint crc = 0; FileInfo fileInfo; string catalogContents = string.Empty; for (int i = 0; i < allAssetBundleNames.Length; i++) { string[] assetPaths = AssetDatabase.GetAssetPathsFromAssetBundle(allAssetBundleNames[i]); if (assetPaths.Length == 0) { JSLDebug.LogErrorFormat("[AssetBundleCatalogBuilder] - The AssetBundle '{0}' is empty. It might be a folder, need to check it again!", allAssetBundleNames[i]); continue; } fullPath = outputPath + "/" + allAssetBundleNames[i]; if (!BuildPipeline.GetCRCForAssetBundle(fullPath, out crc)) { JSLDebug.LogErrorFormat("[AssetBundleCatalogBuilder] - Failed to get CRC from {0}", fullPath); continue; } if (!BuildPipeline.GetHashForAssetBundle(fullPath, out hash128)) { JSLDebug.LogErrorFormat("[AssetBundleCatalogBuilder] - Failed to get Hash128 from {0}", fullPath); continue; } fileInfo = new FileInfo(fullPath); if (!fileInfo.Exists) { JSLDebug.LogErrorFormat("[AssetBundleCatalogBuilder] - Failed to get file size from {0}", fullPath); continue; } if (i != 0) { catalogContents += System.Environment.NewLine; } catalogContents += allAssetBundleNames[i]; catalogContents += System.Environment.NewLine; catalogContents += System.Convert.ToString(hash128); catalogContents += System.Environment.NewLine; catalogContents += crc.ToString(); catalogContents += System.Environment.NewLine; catalogContents += GetFileSizeInB(fileInfo.Length).ToString(); } string catalogPath = Path.Combine(outputPath, AssetBundleDef.CATALOG_FILE_NAME); File.WriteAllText(catalogPath, catalogContents); JSLDebug.LogFormat("[AssetBundleCatalogBuilder] - Build catalog.txt success in {0}", catalogPath); }