/// <summary> /// Different platform's assetBundles is incompatible. /// CosmosEngine put different platform's assetBundles in different folder. /// Here, get Platform name that represent the AssetBundles Folder. /// </summary> /// <returns>Platform folder Name</returns> public static string GetBuildPlatformName() { string buildPlatformName = "Windows"; // default if (Application.isEditor) { var buildTarget = UnityEditor_EditorUserBuildSettings_activeBuildTarget; //UnityEditor.EditorUserBuildSettings.activeBuildTarget; switch (buildTarget) { case "StandaloneOSXIntel": case "StandaloneOSXIntel64": case "StandaloneOSXUniversal": buildPlatformName = "MacOS"; break; case "StandaloneWindows": // UnityEditor.BuildTarget.StandaloneWindows: case "StandaloneWindows64": // UnityEditor.BuildTarget.StandaloneWindows64: buildPlatformName = "Windows"; break; case "Android": // UnityEditor.BuildTarget.Android: buildPlatformName = "Android"; break; case "iPhone": // UnityEditor.BuildTarget.iPhone: case "iOS": buildPlatformName = "iOS"; break; default: Debuger.Assert(false); break; } } else { switch (Application.platform) { case RuntimePlatform.OSXPlayer: buildPlatformName = "MacOS"; break; case RuntimePlatform.Android: buildPlatformName = "Android"; break; case RuntimePlatform.IPhonePlayer: buildPlatformName = "iOS"; break; case RuntimePlatform.WindowsPlayer: #if !UNITY_5_4_OR_NEWER case RuntimePlatform.WindowsWebPlayer: #endif buildPlatformName = "Windows"; break; default: Debuger.Assert(false); break; } } if (Quality != KResourceQuality.Sd) // SD no need add buildPlatformName += Quality.ToString().ToUpper(); return buildPlatformName; }
/// <summary> /// Initialize the path of AssetBundles store place ( Maybe in PersitentDataPath or StreamingAssetsPath ) /// </summary> /// <returns></returns> static void InitResourcePath() { string editorProductPath = EditorProductFullPath; BundlesPathRelative = string.Format("{0}/{1}/", AppConfig.StreamingBundlesFolderName, GetBuildPlatformName()); DocumentResourcesPath = GetFileProtocol() + DocumentResourcesPathWithoutFileProtocol; switch (Application.platform) { case RuntimePlatform.WindowsEditor: case RuntimePlatform.OSXEditor: { ApplicationPath = string.Format("{0}{1}", GetFileProtocol(), editorProductPath); ProductPathWithProtocol = GetFileProtocol() + EditorProductFullPath + "/"; ProductPathWithoutFileProtocol = EditorProductFullPath + "/"; // Resources folder } break; case RuntimePlatform.WindowsPlayer: case RuntimePlatform.OSXPlayer: { string path = Application.streamingAssetsPath.Replace('\\', '/'); //Application.dataPath.Replace('\\', '/'); // path = path.Substring(0, path.LastIndexOf('/') + 1); ApplicationPath = string.Format("{0}{1}", GetFileProtocol(), Application.dataPath); ProductPathWithProtocol = string.Format("{0}{1}/", GetFileProtocol(), path); ProductPathWithoutFileProtocol = string.Format("{0}/", path); // Resources folder } break; case RuntimePlatform.Android: { ApplicationPath = string.Concat("jar:", GetFileProtocol(), Application.dataPath, "!/assets"); ProductPathWithProtocol = string.Concat(ApplicationPath, "/"); ProductPathWithoutFileProtocol = string.Concat(Application.dataPath, "!/assets/"); // 注意,StramingAsset在Android平台中,是在壓縮的apk里,不做文件檢查 // Resources folder } break; case RuntimePlatform.IPhonePlayer: { // MacOSX下,带空格的文件夹,空格字符需要转义成%20 ApplicationPath = System.Uri.EscapeUriString(GetFileProtocol() + Application.streamingAssetsPath); ProductPathWithProtocol = string.Format("{0}/", ApplicationPath); // only iPhone need to Escape the f*****g Url!!! other platform works without it!!! Keng Die! ProductPathWithoutFileProtocol = Application.streamingAssetsPath + "/"; // Resources folder } break; default: { Debuger.Assert(false); } break; } }
private IEnumerator CoLoadSerializeMaterial() { var matLoadBridge = AssetFileLoader.Load(Url); while (!matLoadBridge.IsCompleted) { Progress = matLoadBridge.Progress; yield return(null); } var sMat = matLoadBridge.ResultObject as KSerializeMaterial; Debuger.Assert(sMat); Desc = sMat.ShaderName; Debuger.Assert(Mat == null); yield return(KResourceModule.Instance.StartCoroutine(CoGenerateMaterial(Url, sMat))); Debuger.Assert(Mat); matLoadBridge.Release(); //不需要它了 if (Application.isEditor) { KResoourceLoadedAssetDebugger.Create("Material", Url, Mat); } OnFinish(Mat); }
private IEnumerator CoLoadShader() { var loader = AssetBundleLoader.Load(Url); while (!loader.IsCompleted) { Progress = loader.Progress; yield return(null); } var shader = loader.Bundle.mainAsset as Shader; Debuger.Assert(shader); Desc = shader.name; if (Application.isEditor) { KResoourceLoadedAssetDebugger.Create("Shader", Url, shader); } loader.Release(IsBeenReleaseNow); OnFinish(shader); }
void Start() { IsAppPlaying = true; if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.OSXPlayer) { LogFileManager.Start(); } Debuger.Assert(_isNewByStatic); }
public T this[int index] { get { Debuger.Assert(index < MaxCount); IntPtr p = (IntPtr)(SourceBytesPtr.ToInt32() + Marshal.SizeOf(typeof(T)) * index); return((T)Marshal.PtrToStructure(p, typeof(T))); } }
private void Awake() { if (_Instance != null) { Debuger.Assert(_Instance == this); } //InvokeRepeating("CheckGcCollect", 0f, 3f); }
/// <summary> /// Engine entry.... all begins from here /// </summary> public static AppEngine New(GameObject gameObjectToAttach, IAppEntry entry, IList <IModuleInitable> modules) { Debuger.Assert(gameObjectToAttach != null && modules != null); AppEngine appEngine = gameObjectToAttach.AddComponent <AppEngine>(); appEngine._isNewByStatic = true; appEngine.GameModules = modules; appEngine.AppEntry = entry; return(appEngine); }
/// <summary> /// Engine entry.... all begins from here /// </summary> public static AppEngine New(GameObject gameObjectToAttach, IModule[] modules, CoroutineDelegate before, CoroutineDelegate after) { Debuger.Assert(gameObjectToAttach != null && modules != null); AppEngine appEngine = gameObjectToAttach.AddComponent <AppEngine>(); appEngine.GameModules = modules; appEngine.BeforeInitModules = before; appEngine.AfterInitModules = after; return(appEngine); }
private void Awake() { if (_Instance != null) { Debuger.Assert(_Instance == this); } SpriteAtlasManager.atlasRequested += ABManager.RequestAtlas; if (AppConfig.IsLogDeviceInfo) { //真机上输出这几个路径 Log.Info("ResourceManager AppBasePath:{0} ,AppBasePathWithProtocol:{1}", AppBasePath, AppBasePathWithProtocol); Log.Info("ResourceManager AppDataPath:{0} ,AppDataPathWithProtocol:{1}", AppDataPath, AppDataPathWithProtocol); } }
/// <summary> /// Unity5下,使用manifest进行AssetBundle的加载 /// </summary> static void PreLoadManifest() { if (_hasPreloadAssetBundleManifest) { return; } _hasPreloadAssetBundleManifest = true; //var mainAssetBundlePath = string.Format("{0}/{1}/{1}", KResourceModule.BundlesDirName,KResourceModule.BuildPlatformName); HotBytesLoader bytesLoader = HotBytesLoader.Load(KResourceManager.BuildPlatformName, LoaderMode.Sync); //string.Format("{0}/{1}", KResourceModule.BundlesDirName, KResourceModule.BuildPlatformName), LoaderMode.Sync); _mainAssetBundle = AssetBundle.LoadFromMemory(bytesLoader.Bytes); //KResourceModule.LoadSyncFromStreamingAssets(mainAssetBundlePath)); _assetBundleManifest = _mainAssetBundle.LoadAsset("AssetBundleManifest") as AssetBundleManifest; Debuger.Assert(_mainAssetBundle); Debuger.Assert(_assetBundleManifest); }
private void Awake() { if (_Instance != null) Debuger.Assert(_Instance == this); //InvokeRepeating("CheckGcCollect", 0f, 3f); if (Debug.isDebugBuild) { Log.Info("ResourceManager ApplicationPath: {0}", ApplicationPath); Log.Info("ResourceManager ProductPathWithProtocol: {0}", ProductPathWithProtocol); Log.Info("ResourceManager ProductPathWithoutProtocol: {0}", ProductPathWithoutFileProtocol); Log.Info("ResourceManager DocumentResourcesPath: {0}", DocumentResourcesPath); Log.Info("================================================================================"); } }
private void Awake() { if (_Instance != null) { Debuger.Assert(_Instance == this); } if (AppConfig.IsLogDeviceInfo) { Log.Info("ResourceManager ApplicationPath: {0}", ApplicationPath); Log.Info("ResourceManager ProductPathWithProtocol: {0}", ProductPathWithProtocol); Log.Info("ResourceManager ProductPathWithoutProtocol: {0}", ProductPathWithoutFileProtocol); Log.Info("ResourceManager DocumentResourcesPath: {0}", DocumentResourcesPath); Log.Info("================================================================================"); } }
private string ParseMaterialStr(string materialTextureStr, out Vector2 tiling, out Vector2 offset) { var textureStr = materialTextureStr; // 纹理+tiling+offset var textureArr = textureStr.Split('|'); Debuger.Assert(textureArr.Length > 0); string texturePath = textureArr[0]; tiling = Vector2.one; offset = Vector2.zero; if (textureArr.Length > 1) { tiling = new Vector2(textureArr[1].ToFloat(), textureArr[2].ToFloat()); offset = new Vector2(textureArr[3].ToFloat(), textureArr[4].ToFloat()); } return(texturePath); }
IEnumerator Start() { _assetFileBridge = AssetFileLoader.Load(_url, (bool isOk, UnityEngine.Object obj) => { }, _mode); while (!_assetFileBridge.IsCompleted) { yield return(null); } if (_assetFileBridge.IsError) { Log.Error("[SceneLoader]Load SceneLoader Failed(Error) when Finished: {0}", _url); _assetFileBridge.Release(); OnFinish(null); yield break; } // load scene Debuger.Assert(_assetFileBridge.Asset); if (_mode == LoaderMode.Sync) { UnityEngine.SceneManagement.SceneManager.LoadScene(_sceneName, UnityEngine.SceneManagement.LoadSceneMode.Additive); } else { var op = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(_sceneName, UnityEngine.SceneManagement.LoadSceneMode.Additive); while (!op.isDone) { yield return(null); } } if (Application.isEditor) { KResourceModule.Instance.StartCoroutine(EditorLoadSceneBugFix(null)); } OnFinish(_assetFileBridge); }
/// <summary> /// Unity5下,使用manifest进行AssetBundle的加载 /// bool isForce,在热更新后,可能需要强制刷新AssetBundleManifest。 /// </summary> public static void PreLoadManifest(bool isForce = false) { if (_hasPreloadAssetBundleManifest && isForce == false) { return; } _hasPreloadAssetBundleManifest = true; //此方法不能加载到manifest文件 //var manifestPath = string.Format("{0}/{1}/{1}.manifest", KResourceModule.BundlesPathRelative,KResourceModule.BuildPlatformName); // _mainAssetBundle = AssetBundle.LoadFromFile(manifestPath); // _assetBundleManifest = _mainAssetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest"); KBytesLoader bytesLoader = KBytesLoader.Load(KResourceModule.BundlesPathRelative + KResourceModule.BuildPlatformName, LoaderMode.Sync); _mainAssetBundle = AssetBundle.LoadFromMemory(bytesLoader.Bytes);//KResourceModule.LoadSyncFromStreamingAssets(mainAssetBundlePath)); _assetBundleManifest = _mainAssetBundle.LoadAsset("AssetBundleManifest") as AssetBundleManifest; Debuger.Assert(_mainAssetBundle); Debuger.Assert(_assetBundleManifest); }
/// <summary> /// Unity5下,使用manifest进行AssetBundle的加载 /// bool isForce,在热更新后,可能需要强制刷新AssetBundleManifest。 /// </summary> public static void PreLoadManifest(bool isForce = false) { if (_hasPreloadAssetBundleManifest && isForce == false) { return; } _hasPreloadAssetBundleManifest = true; //此方法不能加载到manifest文件 //var manifestPath = string.Format("{0}/{1}/{1}.manifest", KResourceModule.BundlesPathRelative,KResourceModule.BuildPlatformName); // _mainAssetBundle = AssetBundle.LoadFromFile(manifestPath); // _assetBundleManifest = _mainAssetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest"); var manifestPath = KResourceModule.BundlesPathRelative + KResourceModule.GetBuildPlatformName(); KBytesLoader bytesLoader = KBytesLoader.Load(manifestPath, LoaderMode.Sync); Debuger.Assert(bytesLoader != null, $"load manifest byte error path:{manifestPath}"); _mainAssetBundle = AssetBundle.LoadFromMemory(bytesLoader.Bytes); Debuger.Assert(_mainAssetBundle != null, "load manifest ab error"); _assetBundleManifest = _mainAssetBundle.LoadAsset("AssetBundleManifest") as AssetBundleManifest; }
/// <summary> /// Ensure the CEngineConfig file loaded. /// </summary> public static TableFile <CCosmosEngineInfo> EnsureConfigTab(bool reload = false) { if (_configsTable == null || reload) { string configContent; if (Application.isEditor && !Application.isPlaying) { // prevent Resources.Load fail on Batch Mode configContent = System.IO.File.ReadAllText("Assets/Resources/KEngineConfig.txt"); } else { var textAsset = Resources.Load <TextAsset>("KEngineConfig"); Debuger.Assert(textAsset); configContent = textAsset.text; } _configsTable = new TableFile <CCosmosEngineInfo>(new TableFileConfig { Content = configContent, OnExceptionEvent = (ex, args) => { if (ex != TableFileExceptionType.DuplicatedKey) { var sb = new StringBuilder(); sb.Append(ex.ToString()); sb.Append(": "); foreach (var s in args) { sb.Append(s); sb.Append(", "); } throw new Exception(sb.ToString()); } }, }); } return(_configsTable); }
private IEnumerator _Init(string path, LoaderMode loaderMode) { IsLoadAssetBundle = AppEngine.GetConfig("KEngine", "IsLoadAssetBundle").ToInt32() != 0; Object getAsset = null; if (IsEditorLoadAsset) { #if UNITY_EDITOR if (path.EndsWith(".unity")) { // scene getAsset = KResourceModule.Instance; Log.LogWarning("Load scene from Build Settings: {0}", path); } else { getAsset = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/" + KEngineDef.ResourcesBuildDir + "/" + path, typeof(UnityEngine.Object)); if (getAsset == null) { Log.Error("Asset is NULL(from {0} Folder): {1}", KEngineDef.ResourcesBuildDir, path); } } #else Log.Error("`IsEditorLoadAsset` is Unity Editor only"); #endif OnFinish(getAsset); } else if (!IsLoadAssetBundle) { string extension = Path.GetExtension(path); path = path.Substring(0, path.Length - extension.Length); // remove extensions getAsset = Resources.Load <Object>(path); if (getAsset == null) { Log.Error("Asset is NULL(from Resources Folder): {0}", path); } OnFinish(getAsset); } else { _bundleLoader = AssetBundleLoader.Load(path, null, loaderMode); while (!_bundleLoader.IsCompleted) { if (IsReadyDisposed) // 中途释放 { _bundleLoader.Release(); OnFinish(null); yield break; } yield return(null); } if (!_bundleLoader.IsSuccess) { Log.Error("[AssetFileLoader]Load BundleLoader Failed(Error) when Finished: {0}", path); _bundleLoader.Release(); OnFinish(null); yield break; } var assetBundle = _bundleLoader.Bundle; DateTime beginTime = DateTime.Now; #if UNITY_5 || UNITY_2017_1_OR_NEWER // Unity 5 下,不能用mainAsset, 要取对象名 var abAssetName = Path.GetFileNameWithoutExtension(Url).ToLower(); if (!assetBundle.isStreamedSceneAssetBundle) { if (loaderMode == LoaderMode.Sync) { getAsset = assetBundle.LoadAsset(abAssetName); Debuger.Assert(getAsset); _bundleLoader.PushLoadedAsset(getAsset); } else { var request = assetBundle.LoadAssetAsync(abAssetName); while (!request.isDone) { yield return(null); } Debuger.Assert(getAsset = request.asset); _bundleLoader.PushLoadedAsset(getAsset); } } else { // if it's a scene in asset bundle, did nothing // but set a fault Object the result getAsset = KResourceModule.Instance; } #else // 经过AddWatch调试,.mainAsset这个getter第一次执行时特别久,要做序列化 //AssetBundleRequest request = assetBundle.LoadAsync("", typeof(Object));// mainAsset //while (!request.isDone) //{ // yield return null; //} try { Debuger.Assert(getAsset = assetBundle.mainAsset); } catch { Log.Error("[OnAssetBundleLoaded:mainAsset]{0}", path); } #endif KResourceModule.LogLoadTime("AssetFileBridge", path, beginTime); if (getAsset == null) { Log.Error("Asset is NULL: {0}", path); } } if (Application.isEditor) { if (getAsset != null) { KResoourceLoadedAssetDebugger.Create(getAsset.GetType().Name, Url, getAsset as Object); } // 编辑器环境下,如果遇到GameObject,对Shader进行Fix if (getAsset is GameObject) { var go = getAsset as GameObject; foreach (var r in go.GetComponentsInChildren <Renderer>(true)) { RefreshMaterialsShaders(r); } } } if (getAsset != null) { // 更名~ 注明来源asset bundle 带有类型 getAsset.name = String.Format("{0}~{1}", getAsset, Url); } OnFinish(getAsset); }
void Start() { Debuger.Assert(_isNewByStatic); }
// 加载材质的图片, 协程等待 private IEnumerator CoGenerateMaterial(string matPath, KSerializeMaterial sMat) { // 纹理全部加载完成后到这里 //if (!CachedMaterials.TryGetValue(matPath, out mat)) { var shaderLoader = ShaderLoader.Load(sMat.ShaderPath); while (!shaderLoader.IsCompleted) { yield return(null); } var shader = shaderLoader.ShaderAsset; if (shader == null) { shader = KTool.FindShader(sMat.ShaderName); Log.Warning("无法加载Shader资源: {0}, 使用Shaders.Find代替", sMat.ShaderName); if (shader == null) { Log.Warning("找不到Shader: {0}, 使用Diffuse临时代替", sMat.ShaderName); shader = KTool.FindShader("Diffuse"); } } Debuger.Assert(shader); Mat = new Material(shader); Mat.name = sMat.MaterialName; //CachedMaterials[matPath] = mat; foreach (KSerializeMaterialProperty shaderProp in sMat.Props) { switch (shaderProp.Type) { case KSerializeMaterialProperty.ShaderType.Texture: Vector2 tiling; Vector2 offset; var texturePath = ParseMaterialStr(shaderProp.PropValue, out tiling, out offset); if (TextureLoaders == null) { TextureLoaders = new List <TextureLoader>(); } var texLoader = TextureLoader.Load(texturePath); TextureLoaders.Add(texLoader); while (!texLoader.IsCompleted) { yield return(null); } var tex = texLoader.Asset; if (tex == null) { Log.Error("找不到纹理: {0}", texturePath); } else { _SetMatTex(Mat, shaderProp.PropName, tex, tiling, offset); } break; case KSerializeMaterialProperty.ShaderType.Color: _SetMatColor(Mat, shaderProp.PropName, shaderProp.PropValue); break; case KSerializeMaterialProperty.ShaderType.Range: _SetMatRange(Mat, shaderProp.PropName, shaderProp.PropValue); break; case KSerializeMaterialProperty.ShaderType.Vector: _SetMatVector(Mat, shaderProp.PropName, shaderProp.PropValue); break; case KSerializeMaterialProperty.ShaderType.RenderTexture: // RenderTextures, 不处理, 一般用在水,Water脚本会自动生成 break; } } } }
// 将字符串转成指定类型的数组 , 单元测试在Test_StrBytesToArray public static T[] StrBytesToArray <T>(string str, int arraySize) { int typeSize = Marshal.SizeOf(typeof(T)); byte[] strBytes = Encoding.Unicode.GetBytes(str); byte[] bytes = new byte[typeSize * arraySize]; // 强制数组大小 for (int k = 0; k < strBytes.Length; k++) { bytes[k] = strBytes[k]; // copy } T[] tArray = new T[bytes.Length / typeSize]; // 总字节 除以 类型长度 = 有多少个类型对象 int offset = 0; for (int i = 0; i < tArray.Length; i++) { object convertedObj = null; TypeCode typeCode = Type.GetTypeCode(typeof(T)); switch (typeCode) { case TypeCode.Byte: convertedObj = bytes[offset]; break; case TypeCode.Int16: convertedObj = BitConverter.ToInt16(bytes, offset); break; case TypeCode.Int32: convertedObj = BitConverter.ToInt32(bytes, offset); break; case TypeCode.Int64: convertedObj = BitConverter.ToInt64(bytes, offset); break; case TypeCode.UInt16: convertedObj = BitConverter.ToUInt16(bytes, offset); break; case TypeCode.UInt32: convertedObj = BitConverter.ToUInt32(bytes, offset); break; case TypeCode.UInt64: convertedObj = BitConverter.ToUInt64(bytes, offset); break; default: Log.Error("Unsupport Type {0} in StrBytesToArray(), You can custom this.", typeCode); Debuger.Assert(false); break; } tArray[i] = (T)(convertedObj); offset += typeSize; } return(tArray); }
/// <summary> /// Initialize the path of AssetBundles store place ( Maybe in PersitentDataPath or StreamingAssetsPath ) /// </summary> /// <returns></returns> static void InitResourcePath() { GameObject resMgr = GameObject.Find("_ResourceModule_"); if (resMgr == null) { resMgr = new GameObject("_ResourceModule_"); GameObject.DontDestroyOnLoad(resMgr); } _Instance = resMgr.AddComponent <KResourceModule>(); string editorProductPath = EditorProductFullPath; BundlesPathRelative = string.Format("{0}/{1}/", BundlesDirName, GetBuildPlatformName()); DocumentResourcesPath = FileProtocol + DocumentResourcesPathWithoutFileProtocol; switch (Application.platform) { case RuntimePlatform.WindowsEditor: case RuntimePlatform.OSXEditor: { ApplicationPath = string.Format("{0}{1}/", GetFileProtocol(), editorProductPath); BundlesPathWithProtocol = GetFileProtocol() + EditorAssetBundleFullPath + "/" + BuildPlatformName + "/"; BundlesPathWithoutFileProtocol = EditorAssetBundleFullPath + "/" + BuildPlatformName + "/"; // Resources folder } break; case RuntimePlatform.WindowsPlayer: case RuntimePlatform.OSXPlayer: { string path = Application.streamingAssetsPath.Replace('\\', '/'); //Application.dataPath.Replace('\\', '/'); // path = path.Substring(0, path.LastIndexOf('/') + 1); ApplicationPath = string.Format("{0}{1}/", GetFileProtocol(), Application.dataPath); BundlesPathWithProtocol = string.Format("{0}{1}/{2}/{3}/", GetFileProtocol(), path, BundlesDirName, GetBuildPlatformName()); BundlesPathWithoutFileProtocol = string.Format("{0}/{1}/{2}/", path, BundlesDirName, GetBuildPlatformName()); // Resources folder } break; case RuntimePlatform.Android: { ApplicationPath = string.Concat("jar:", GetFileProtocol(), Application.dataPath, string.Format("!/assets/{0}/", BundlesDirName)); BundlesPathWithProtocol = string.Concat(ApplicationPath, GetBuildPlatformName(), "/"); BundlesPathWithoutFileProtocol = string.Concat(Application.dataPath, "!/assets/" + BundlesDirName + "/", GetBuildPlatformName() + "/"); // 注意,StramingAsset在Android平台中,是在壓縮的apk里,不做文件檢查 // Resources folder } break; case RuntimePlatform.IPhonePlayer: { ApplicationPath = System.Uri.EscapeUriString(GetFileProtocol() + Application.streamingAssetsPath + "/" + BundlesDirName + "/"); // MacOSX下,带空格的文件夹,空格字符需要转义成%20 BundlesPathWithProtocol = string.Format("{0}{1}/", ApplicationPath, GetBuildPlatformName()); // only iPhone need to Escape the f*****g Url!!! other platform works without it!!! Keng Die! BundlesPathWithoutFileProtocol = Application.streamingAssetsPath + "/" + BundlesDirName + "/" + GetBuildPlatformName() + "/"; // Resources folder } break; default: { Debuger.Assert(false); } break; } }
private IEnumerator _Init(string path, LoaderMode loaderMode) { IsLoadAssetBundle = KEngine.AppEngine.GetConfig("KEngine", "IsLoadAssetBundle").ToInt32() != 0; UnityEngine.Object getAsset = null; if (!IsLoadAssetBundle) { string extension = System.IO.Path.GetExtension(path); path = path.Substring(0, path.Length - extension.Length); // remove extensions getAsset = Resources.Load <UnityEngine.Object>(path); if (getAsset == null) { Log.Error("Asset is NULL(from Resources Folder): {0}", path); } OnFinish(getAsset); } else { _bundleLoader = KAssetBundleLoader.Load(path, null, loaderMode); while (!_bundleLoader.IsCompleted) { if (IsReadyDisposed) // 中途释放 { _bundleLoader.Release(); OnFinish(null); yield break; } yield return(null); } if (!_bundleLoader.IsSuccess) { Log.Error("[KAssetFileLoader]Load BundleLoader Failed(Error) when Finished: {0}", path); _bundleLoader.Release(); OnFinish(null); yield break; } var assetBundle = _bundleLoader.Bundle; System.DateTime beginTime = System.DateTime.Now; #if UNITY_5 // Unity 5 下,不能用mainAsset, 要取对象名 var abAssetName = Path.GetFileNameWithoutExtension(Url).ToLower(); if (loaderMode == LoaderMode.Sync) { getAsset = assetBundle.LoadAsset(abAssetName); Debuger.Assert(getAsset); } else { var request = assetBundle.LoadAssetAsync(abAssetName); while (!request.isDone) { yield return(null); } Debuger.Assert(getAsset = request.asset); } #else // 经过AddWatch调试,.mainAsset这个getter第一次执行时特别久,要做序列化 //AssetBundleRequest request = assetBundle.LoadAsync("", typeof(Object));// mainAsset //while (!request.isDone) //{ // yield return null; //} try { Debuger.Assert(getAsset = assetBundle.mainAsset); } catch { Log.Error("[OnAssetBundleLoaded:mainAsset]{0}", path); } #endif KResourceModule.LogLoadTime("AssetFileBridge", path, beginTime); if (getAsset == null) { Log.Error("Asset is NULL: {0}", path); } } if (Application.isEditor) { if (getAsset != null) { KResoourceLoadedAssetDebugger.Create(getAsset.GetType().Name, Url, getAsset as UnityEngine.Object); } } if (getAsset != null) { // 更名~ 注明来源asset bundle 带有类型 getAsset.name = string.Format("{0}~{1}", getAsset, Url); } OnFinish(getAsset); }
/// <summary> /// Initialize the path of AssetBundles store place ( Maybe in PersitentDataPath or StreamingAssetsPath ) /// </summary> /// <returns></returns> static void InitResourcePath() { string editorProductPath = EditorProductFullPath; BundlesPathRelative = string.Format("{0}/{1}/", AppConfig.StreamingBundlesFolderName, GetBuildPlatformName()); string fileProtocol = GetFileProtocol; AppDataPathWithProtocol = fileProtocol + AppDataPath; switch (Application.platform) { case RuntimePlatform.WindowsEditor: case RuntimePlatform.OSXEditor: case RuntimePlatform.LinuxEditor: { if (AppConfig.ReadStreamFromEditor) { AppBasePath = Application.streamingAssetsPath + "/"; AppBasePathWithProtocol = fileProtocol + AppBasePath; } else { AppBasePath = editorProductPath + "/"; AppBasePathWithProtocol = fileProtocol + AppBasePath; } } break; case RuntimePlatform.WindowsPlayer: case RuntimePlatform.OSXPlayer: { string path = Application.streamingAssetsPath.Replace('\\', '/'); AppBasePath = path + "/"; AppBasePathWithProtocol = fileProtocol + AppBasePath; } break; case RuntimePlatform.Android: { //文档:https://docs.unity3d.com/Manual/StreamingAssets.html //注意,StramingAsset在Android平台是在apk中,无法通过File读取请使用LoadAssetsSync,如果要同步读取ab请使用GetAbFullPath AppBasePath = Application.dataPath + "!/assets/"; AppBasePathWithProtocol = fileProtocol + AppBasePath; } break; case RuntimePlatform.IPhonePlayer: { // MacOSX下,带空格的文件夹,空格字符需要转义成%20 // only iPhone need to Escape the f*****g Url!!! other platform works without it!!! AppBasePath = System.Uri.EscapeUriString(Application.dataPath + "/Raw"); AppBasePathWithProtocol = fileProtocol + AppBasePath; } break; default: { Debuger.Assert(false); } break; } }