Exemplo n.º 1
0
        /// <summary>
        /// Different platform's assetBundles is incompatible.// ex: IOS, Android, Windows
        /// KEngine 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":
                case "StandaloneOSX":
                    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);
        }
Exemplo n.º 2
0
        // 将字符串转成指定类型的数组 , 单元测试在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);
        }
Exemplo n.º 3
0
 void Start()
 {
     Debuger.Assert(_isNewByStatic);
 }
Exemplo n.º 4
0
        /// <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
                //NOTE 我见到一些项目的做法是把apk包内的资源放到Assets的上层res内,读取时使用 jar:file://+Application.dataPath + "!/assets/res/",editor上则需要/../res/
                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;
            }
        }
Exemplo n.º 5
0
        // 加载材质的图片, 协程等待
        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;
                    }
                }
            }
        }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
        /// <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;
            }
        }
Exemplo n.º 8
0
        /// <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}/", BundlesDirName, GetBuildPlatformName());
            DocumentResourcesPath = FileProtocol + 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:
            {
                ApplicationPath =
                    System.Uri.EscapeUriString(GetFileProtocol() + Application.streamingAssetsPath);         // MacOSX下,带空格的文件夹,空格字符需要转义成%20

                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;
            }
        }
Exemplo n.º 9
0
        private IEnumerator _Init(string path, LoaderMode loaderMode)
        {
            IsLoadAssetBundle = AppEngine.GetConfig("KEngine", "IsLoadAssetBundle").ToInt32() != 0;

            Object getAsset = null;

            if (KResourceModule.IsEditorLoadAsset && Application.isEditor)
            {
#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
            }
            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);
                }
            }
            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);
        }