Beispiel #1
0
        public static T LoadData <T>(string key)
        {
            if (!PlayerPrefs.HasKey(key))
            {
                return(default(T));
            }

            try {
                T ret;
                if (typeof(T) == typeof(int) || typeof(T) == typeof(uint))
                {
                    ret = (T)Convert.ChangeType(PlayerPrefs.GetInt(key), typeof(T));
                }
                else if (typeof(T) == typeof(float) || typeof(T) == typeof(double))
                {
                    ret = (T)Convert.ChangeType(PlayerPrefs.GetFloat(key), typeof(T));
                }
                else if (typeof(T) == typeof(string))
                {
                    ret = (T)Convert.ChangeType(PlayerPrefs.GetString(key), typeof(T));
                }
                else
                {
                    string txt = PlayerPrefs.GetString(key);
                    ret = JsonUtility.FromJson <T>(txt);
                }

                return(ret);
            } catch (Exception e) {
                Logger.LogWarning("读取配置错误, key = " + key + ", " + e);
            }

            return(default(T));
        }
Beispiel #2
0
 // 加载资源
 public void LoadAsset(string path, Type type, LoadedHandler onLoaded,
                       bool async            = true, bool persistent = false, bool inData = true,
                       LoadPriority priority = LoadPriority.Normal)
 {
     //Logger.Log(string.Format("LoadAsset: {0} - {1}", path, async));
     if (ConstantData.EnableAssetBundle)
     {
         string abName = m_mapping.GetAssetBundleNameFromAssetPath(path);
         if (string.IsNullOrEmpty(abName))
         {
             Logger.LogError(string.Format("找不到资源所对应的ab文件:{0}", path));
             if (onLoaded != null)
             {
                 onLoaded(null);
             }
         }
         else
         {
             string assetName = Path.GetFileName(path);
             LoadAssetFromBundle(null, abName, assetName, type, (group, data) => {
                 if (onLoaded != null)
                 {
                     onLoaded(data);
                 }
             }, async, persistent, priority);
         }
     }
     else
     {
         LoadAssetFile(path, onLoaded, type, async, inData, priority);
     }
 }
Beispiel #3
0
        public string GetResourcePath(string name, bool async = false)
        {
            if (ConstantData.EnableCache)
            {
                string md5;
                if (m_patchs.TryGetValue(name, out md5))
                {
                    if (async)
                    {
                        // 异步加载,返回远程路径
                        return(string.Format("{0}/{1}{2}", m_urlPatch, md5, ConstantData.AssetBundleExt));
                    }
                    else
                    {
                        // 同步加载,返回缓存路径
                        string path = FileHelper.GetCacheAssetBundlePath(md5);
                        if (File.Exists(path))
                        {
                            return(path);
                        }
                    }
                }

                if (m_origns.TryGetValue(name, out md5))
                {
                    return(string.Format("{0}/{1}{2}", ConstantData.StreamingAssetsPath, md5,
                                         ConstantData.AssetBundleExt));
                }

                Logger.LogError(string.Format("Get MD5 failed: {0}", name));
                return("");
            }
            else
            {
                string path = name;
                if (ConstantData.EnableMd5Name)
                {
                    string md5;
                    if (m_patchs.TryGetValue(name, out md5))
                    {
                        path = SearchPath(md5, true, true);
                        if (!string.IsNullOrEmpty(path))
                        {
                            return(path);
                        }
                    }

                    if (!m_origns.TryGetValue(name, out md5))
                    {
                        Logger.LogError(string.Format("Get MD5 failed: {0}", name));
                        return("");
                    }

                    path = md5;
                }

                return(SearchPath(path, false, true));
            }
        }
Beispiel #4
0
        /// <summary>
        /// 保存直接流到文件
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool SaveBytesToFile(byte[] bytes, string path)
        {
            CreateDirectoryFromFile(path);

            try {
                Stream stream = File.Open(path, FileMode.Create);
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();
                return(true);
            } catch (Exception e) {
                Logger.LogError(e.Message);
                return(false);
            }
        }
Beispiel #5
0
        public override void Load()
        {
            base.Load();

            string path = LoadMgr.Inst.GetResourcePath(Path);

            if (string.IsNullOrEmpty(path))
            {
                OnLoaded(null);
                return;
            }

            m_needUnpack = ConstantData.EnableCustomCompress && path.Contains(ConstantData.StreamingAssetsPath);

            if (IsAsync)
            {
                if (m_needUnpack)
                {
                    m_stageCount = 2;

                    byte[] bytes = FileHelper.ReadByteFromFile(path);
                    m_unpackRequest = LzmaCompressRequest.CreateDecompress(bytes);
                }
                else
                {
                    m_abRequest = AssetBundle.LoadFromFileAsync(path);
                }
            }
            else
            {
                AssetBundle ab = null;
                try {
                    if (m_needUnpack)
                    {
                        byte[] bytes = FileHelper.ReadByteFromFile(path);
                        bytes = Unpack(bytes);
                        ab    = AssetBundle.LoadFromMemory(bytes);
                    }
                    else
                    {
                        ab = AssetBundle.LoadFromFile(path);
                    }
                } catch (Exception e) {
                    Logger.LogError(e.Message);
                }
                finally {
                    OnLoaded(ab);
                }
            }
        }
Beispiel #6
0
        public void Dump()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("Dump Bundle Cache. Count = {0}\n", m_caches.Count);
            var iter = m_caches.GetEnumerator();

            while (iter.MoveNext())
            {
                AssetBundleInfo item = iter.Current.Value;
                sb.AppendFormat("{0} count:{1} persistent:{2}\n", iter.Current.Key, item.ReferencedCount,
                                item.Persistent);
            }

            iter.Dispose();

            Logger.Log(sb.ToString());
        }
Beispiel #7
0
        ///  <summary>
        ///
        ///  </summary>
        ///  <param name="msg"></param>
        ///  <param name="level"></param>
        /// <param name="isGlobal">是否是全局LOG</param>
        protected void Log(string msg, LogLevel level = LogLevel.Error, bool isGlobal = false)
        {
            if (!isGlobal)
            {
                msg = string.Format("[第{0}行,列名:{1}] {2}", m_curRowIndex, m_curColName, msg);
            }

            msg = string.Format("配置错误({0}.csv) => {1}", GetName(), msg);
            switch (level)
            {
            case LogLevel.Warning:
                Logger.LogWarning(msg, "BaseCfgDecoder.LogCfgError");
                break;

            default:
                Logger.LogError(msg, "BaseCfgDecoder.LogCfgError");
                break;
            }
        }
Beispiel #8
0
        public override void Load()
        {
            base.Load();

            if (IsAsync)
            {
                string path = Path;

                bool hasHead = (bool)Param;
                if (!hasHead)
                {
                    bool addFileHead = true;

#if UNITY_ANDROID && !UNITY_EDITOR
                    // 如果是读取apk里的资源,不需要加file:///,其它情况都要加
                    if (path.Contains(Application.streamingAssetsPath))
                    {
                        addFileHead = false;
                    }
#endif
                    // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                    if (addFileHead)
                    {
                        path = string.Format("file:///{0}", path);
                    }
                }

                m_request = new WWW(path);
            }
            else
            {
                object data = null;
                try {
                    data = FileHelper.ReadByteFromFile(Path);
                } catch (Exception e) {
                    Logger.LogError(e.Message);
                }
                finally {
                    OnLoadCompleted(data);
                }
            }
        }
Beispiel #9
0
        // ------------------------------------------------------------------------------------------
        // 编辑器专用加载
        // 加载Assets目录下的文件(编辑器专用,带后缀)
        public void LoadFile(string path, LoadedHandler onLoaded,
                             bool async = true, bool inData = true, LoadPriority priority = LoadPriority.Normal)
        {
#if !UNITY_EDITOR && !UNITY_STANDALONE
            Logger.LogError("LoadFile为编辑器专用方法!");
            return;
#endif

            string fullpath = string.Format("{0}/{1}", inData ? ConstantData.DataFullPath : Application.dataPath, path);
            if (!CheckFileExist(fullpath, onLoaded))
            {
                return;
            }

            m_task.AddLoadTask(null, Loader.LoaderType.Stream, fullpath, false, (group, data) => {
                if (onLoaded != null)
                {
                    onLoaded(data);
                }
            }, async, priority);
        }
Beispiel #10
0
        /*private void InitVersionData(bool start = true)
         * {
         *  Clear();
         *
         *  m_origns.Clear();
         *  for (int i = 0; i < VersionData.Inst.Items.Length; ++i)
         *  {
         *      VersionData.VersionItem item = VersionData.Inst.Items[i];
         *      m_origns.Add(item.Name, item.Md5);
         *  }
         *
         *  if (start)
         *  {
         *      LoadManifest();
         *  }
         * }*/

        /*public void SetPatchData(JSONClass list, bool clear = false)
         * {
         *  if (clear)
         *  {
         *      Clear();
         *  }
         *
         *  m_patchs.Clear();
         *  if (list != null)
         *  {
         *      foreach (KeyValuePair<string, JSONNode> item in list)
         *      {
         *          m_patchs.Add(item.Key, item.Value["md5"]);
         *      }
         *  }
         *
         *  LoadManifest();
         * }*/

        /*private void LoadVersion()
         * {
         *  Logger.Log("LoadVersion");
         *  if (ConstantData.EnableMd5Name)
         *  {
         *      string pathPatch = string.Format("{0}/version_patch", Application.persistentDataPath);
         *      bool hasPatch = false;
         *
         *      if (ConstantData.EnablePatch)
         *      {
         *          hasPatch = File.Exists(pathPatch);
         *      }
         *
         *      InitVersionData(!hasPatch);
         *
         *      if (hasPatch)
         *      {
         *          LoadStream(pathPatch, (data) =>
         *          {
         *              byte[] bytes = data as byte[];
         *              if (bytes == null)
         *              {
         *                  Logger.LogError("Load patch version Failed!");
         *                  return;
         *              }
         *
         *              string text = Encoding.UTF8.GetString(bytes);
         *              JSONClass json = JSONNode.Parse(text) as JSONClass;
         *              if (json == null)
         *              {
         *                  Logger.LogError("Load patch version Failed!");
         *                  return;
         *              }
         *
         *              JSONClass jsonList = null;
         *              if (string.Equals(json["version"], LogicConstantData.Version))
         *              {
         *                  jsonList = json["list"] as JSONClass;
         *              }
         *
         *              m_urlPatch = json["url"];
         *              SetPatchData(jsonList);
         *          }, false, false, true);
         *      }
         *  }
         *  else
         *  {
         *      LoadManifest();
         *  }
         * }*/

        // 加载资源清单
        private void LoadManifest()
        {
            Logger.Log("LoadManifest");

            if (m_manifest != null)
            {
                Object.DestroyImmediate(m_manifest, true);
                m_manifest = null;
            }

            if (m_mapping != null)
            {
                Object.DestroyImmediate(m_mapping, true);
                m_mapping = null;
            }

            // 加载AssetBundle依赖文件
            LoadAssetBundle(null, ConstantData.AssetbundleManifest, (group, data) => {
                AssetBundleInfo ab = data as AssetBundleInfo;
                if (ab != null)
                {
                    m_manifest = ab.LoadAsset <AssetBundleManifest>("AssetBundleManifest");
                }
            }, false, false, false);

            // 加载资源到AssetBundle映射表
            string name = ConstantData.AssetbundleMapping;

            LoadAssetFromBundle(null, name, name, typeof(AssetBundleMapping), (group, data) => {
                m_mapping = data as AssetBundleMapping;
                if (m_mapping != null)
                {
                    m_mapping.Init();
                }
            }, false);

            Logger.Log("LoadManifest End");
        }
Beispiel #11
0
 /// <summary>
 /// 更新
 /// </summary>
 public override void Update()
 {
     if (State == LoaderState.Loading)
     {
         if (m_request == null)
         {
             OnLoadCompleted(null);
         }
         else if (!string.IsNullOrEmpty(m_request.error))
         {
             Logger.LogError(m_request.error);
             OnLoadCompleted(null);
         }
         else if (m_request.isDone)
         {
             OnLoadCompleted(m_request.bytes);
         }
         else
         {
             OnLoadProgress(m_request.progress);
         }
     }
 }
Beispiel #12
0
        // 加载AssetBundle(先从persistentData读,没有找到则从streamingAssets读,带后缀)
        private void LoadAssetBundle(LoaderGroup group, string path, GroupLoadedCallback onLoaded,
                                     bool async            = true, bool persistent = false, bool manifest = true,
                                     LoadPriority priority = LoadPriority.Normal)
        {
            path = path.ToLower();

            if (async && group == null)
            {
                group = m_task.PopGroup(priority);
            }

            if (manifest)
            {
                if (!HasBundle(path))
                {
                    // Manifest里没有这个AssetBundle,说明是一个错误的路径
                    Logger.LogError(string.Format("ab不存在:{0}", path));
                    if (onLoaded != null)
                    {
                        if (!async)
                        {
                            onLoaded(group, null);
                        }
                        else
                        {
                            m_task.AddAsyncCallback(onLoaded, group, null);
                        }
                    }

                    return;
                }

                // 加载依赖
                LoadDependencies(group, path, async, persistent);
            }

            // 检查是否有缓存
            if (m_cache.CheckAssetBundleInfo(group, path, onLoaded, persistent, async))
            {
                return;
            }

            // 添加加载任务
            m_task.AddLoadTask(group, Loader.LoaderType.Bundle, path, null, (group1, data) => {
                AssetBundle ab       = data as AssetBundle;
                AssetBundleInfo info = null;

                if (ab != null)
                {
                    info = m_cache.SetAssetBundle(path, ab);
#if UNITY_EDITOR
                    RefreshShader(ab);
#endif
                }

                // 加载回调
                if (onLoaded != null)
                {
                    onLoaded(group1, info);
                }
            }, async, priority);
        }