private AssetBundleRequest m_cRequest; //The load request

    #endregion Fields

    #region Methods

    /// <summary>
    /// Start async load the assetbundle
    /// </summary>
    /// <param name="asset"></param>
    /// <param name="resName"></param>
    /// <param name="callback"></param>
    public static AsyncLoader StartLoad(AssetBundle asset, string resName)
    {
        GameObject obj = new GameObject("AsyncLoader");
        AsyncLoader loader = obj.AddComponent<AsyncLoader>();
        loader.StartCoroutine(loader.GoLoader(asset, resName));
        return loader;
    }
示例#2
0
    void Start()
    {
        m_cube = AssetBundle.LoadFromFile("C:\\Users\\yunsubaek_df\\Documents\\AssetBundleTest1\\AssetBundles\\Windows\\cube-bundle");

        cube_obj = (GameObject)m_cube.LoadAsset<GameObject>("Cube");
        GameObject.Instantiate(cube_obj,new Vector3(1,1,1),Quaternion.identity);
    }
示例#3
0
    static void AddLoadedBundleToManager(AssetBundle bundle, string name)
    {
        if (!isBundleLoaded(bundle, name))
            return;

        AssetBundleManager.AddBundle(name, 0, bundle);
    }
示例#4
0
    void OnAssetBundleLoaded(string url, AssetBundle assetBundle, params object[] args)
    {
        Object asset = null;
        System.DateTime beginTime = System.DateTime.Now;
        if (AssetInBundleName == null)
        {
            // 经过AddWatch调试,.mainAsset这个getter第一次执行时特别久,要做序列化
            try
            {
                asset = assetBundle.mainAsset;
            }
            catch
            {
                CBase.LogError("[OnAssetBundleLoaded:mainAsset]{0}", url);
            }
        }
        else
        {
            AssetBundleRequest request = assetBundle.LoadAsync(AssetInBundleName, typeof(Object));
            asset = request.asset;
        }

        CResourceManager.LogLoadTime("AssetFileBridge", url, beginTime);

        if (asset == null)
        {
            CBase.LogError("Asset is NULL: {0}", url);
        }

        AssetFileLoadedCallback(asset, CallbackArgs);
    }
示例#5
0
    IEnumerator _LoadAssets(Action loadComplete, Action loadError)
    {
        if (Debug.isDebugBuild)
            _loader = new WWW(Main.HOST + _versionBundle.url);
        else
            _loader = WWW.LoadFromCacheOrDownload(Main.HOST + _versionBundle.url, _versionBundle.versionValue);
        yield return _loader;

        if (string.IsNullOrEmpty(_loader.error))
        {
            if (_versionBundle.isEncrypted)
            {
                TextAsset encryped = _loader.assetBundle.Load(BundleLoader.ENCRYPTED_DATA, typeof(TextAsset)) as TextAsset;
                byte[] encryptedData = encryped.bytes;
                byte[] decryptedData = _Decrypt(encryptedData);
                _bundle = AssetBundle.CreateFromMemory(decryptedData).assetBundle;
            }
            else
            {
                _bundle = _loader.assetBundle;
            }

            _isLoadComplete = true;

            if (loadComplete != null) loadComplete();
        }
        else
        {
            Debug.LogError("Error: Load asset error with url: " + Main.HOST + _versionBundle.url + " - " + _loader.error);
            if (loadError != null) loadError();
        }
    }
示例#6
0
 /// <summary>
 /// 创建
 /// </summary>
 /// <param name="decryptedData"></param>
 /// <returns></returns>
 IEnumerator LoadBundle(byte[] decryptedData)
 {
     AssetBundleCreateRequest acr = AssetBundle.CreateFromMemory(decryptedData);
     yield return acr;
     assetBundel = acr.assetBundle;
     Instantiate(assetBundel.Load("Cube"));
 }
示例#7
0
文件: Test.cs 项目: Dotby/SpaceViever
 IEnumerator DownloadAB()
 {
     Debug.Log("downloading...");
         yield return StartCoroutine(AssetBundleManager.downloadAssetBundle (url, version));
         bundle = AssetBundleManager.getAssetBundle (url, version);
         Debug.Log("complete");
         Debug.Log(bundle);
 }
示例#8
0
文件: Test.cs 项目: Dotby/SpaceViever
 void OnGUI()
 {
     if (GUILayout.Button ("Download bundle")){
         bundle = AssetBundleManager.getAssetBundle (url, version);
         if(!bundle)
             StartCoroutine (DownloadAB());
     }
 }
示例#9
0
 public void decRef()
 {
     if(--loadReq == 0)
     {
         bundle.Unload(false);
         bundle = null;
     }
 }
示例#10
0
    private void BundleLoadedHandler(WWW request)
    {
        Debug.Log("Bundle loaded: " + request.url);
        _bundle = request.assetBundle;

        AssetBundleRequest assetBundleRequest = _bundle.LoadAsync(AssetName, typeof(GameObject));
        _assetBundleQueue.Send(assetBundleRequest, AssetLoadedHandler);
    }
 public IEnumerator LoadBundleFromFileUncompressed(string path)
 {
     CheckFileExists(path);
     bundle = AssetBundle.CreateFromFile(path);
     CheckBundle(bundle);
     Debug.Log("loaded bundle: " + path);
     yield return null;
 }
示例#12
0
 public void Unload(bool unloadAllLoadedObjects)
 {
     if (_bundle != null)
     {
         _bundle.Unload(unloadAllLoadedObjects);
         _bundle = null;
     }
     _loader = null;
 }
    /// <summary>
    /// Begin load
    /// </summary>
    /// <param name="asset"></param>
    /// <param name="resName"></param>
    /// <returns></returns>
    public IEnumerator GoLoader(AssetBundle asset, string resName)
    {
        this.m_cRequest = asset.LoadAsync(resName, typeof(UnityEngine.Object));

        for (; !this.m_cRequest.isDone; )
            yield return this.m_cRequest;

        GameObject.Destroy(this.gameObject);
    }
示例#14
0
 public void UnLoad()
 {
     loadReq = 0;
     if(bundle != null)
     {
         bundle.Unload(false);
         bundle = null;
     }
 }
    /// <summary>
    /// 初始化
    /// </summary>
    void initialize() {
        string uri = string.Empty;
        //------------------------------------Shared--------------------------------------
        uri = Util.DataPath + "shared.assetbundle";
        Debug.LogWarning("LoadFile::>> " + uri);

        shared = AssetBundle.CreateFromFile(uri);
        shared.Load("Dialog", typeof(GameObject));
        ioo.gameManager.OnResourceInited();    //回调游戏管理器,执行后续操作 
    }
 public IEnumerator LoadBundleFromMemory(byte[] buffer)
 {
     AssetBundleCreateRequest bundleRequest = AssetBundle.CreateFromMemory(buffer);
     yield return bundleRequest;
     if (bundleRequest.isDone)
     {
         bundle = bundleRequest.assetBundle;
         CheckBundle(bundle);
     }
 }
	public IABManifestLoader()
	{
		assetManifest = null;

		manifestLoader = null;

		IsLoadFinish = false;

		manifestPath = IPathTools.GetABPath ();
	}
示例#18
0
    public MapHandler(IMapLoader mapLoader, AssetBundle mapAsset, MapSettings mapSettings, int mapLayer)
    {
        this.mapLoader = mapLoader;
        this.bundle = mapAsset;
        this.mapSettings = mapSettings;
        this.mapLayer = mapLayer;

        this.mapOffset = new Vector3(mapSettings.length / 2, HUDConstants.MAP_HEIGHT, mapSettings.width / 2);
        this.mapBounds = new Rect();
    }
示例#19
0
 public AssetBundleRequest Load(string name, Type type)
 {
     Debug.Log("Loading " + name);
     if (null == bundle)
     {
         bundle = www.assetBundle;
         www.Dispose();
     }
     return bundle.LoadAsync(name, type);
 }
示例#20
0
 private GameObject loadSprite(string spriteName)
 {
     #if USE_ASSETBUNDLE
     if(assetbundle == null)
         assetbundle = AssetBundle.CreateFromFile(Application.streamingAssetsPath +"/Main.assetbundle");
             return assetbundle.Load(spriteName) as Sprite;
     #else
     return Instantiate(Resources.Load<GameObject>("Prefab/Atlas/Public/" + spriteName)) as GameObject;
     #endif
 }
    public IEnumerator LoadAssetsFromBundle(AssetBundle bundle, string[] names)
    {
        objects = new List<Object>();

        foreach (var name in names)
        {
            Object obj = bundle.Load(name);
            TryAddAsset(name, obj, objects);
        }
        yield return null;
    }
示例#22
0
    static bool isBundleLoaded(AssetBundle bundle, string name)
    {
        if (bundle == null)
        {
            Debug.LogWarning(string.Format("Bundle {0} is not loaded", name));
            return false;
        }

        Debug.Log(string.Format("Bundle {0} is loaded", name));
        return true;
    }
    IEnumerator NewObject()
    {
        if (this.assetBundle != null && this.assetBundle.Contains(this.assetBundle.mainAsset.name)){
            Debug.Log ("unload asset");
            this.assetBundle.Unload(false);
        }
        WWW www = new WWW(this.assetBundleURL);
        yield return www;

        this.assetBundle = www.assetBundle;
    }
示例#24
0
 //AudioClip sound;
 //AudioClip soundShoot;
 void Start()
 {
     sphereBundle = Utilities.GetBundle(SphereScript.SphereBundlePath);
     audio.clip = AudioUtilities.MainSound;
     if(audio.clip != null)
     {
         audio.Play();
     }
     TextureUtils.FillTextures();
     DoWork();
 }
示例#25
0
	public static void addAssetBundle(string url, int version, AssetBundle assetbundle )
	{
		Debug.Log("addAssetBundle url = "+ url);
		if( getAssetBundle(url, version ) == null )
		{
			Debug.Log("addAssetBundle Success");
			string keyName = url + version.ToString();
			AssetBundleRef abRef = new AssetBundleRef (url, version);
			abRef.assetBundle = assetbundle;
			dictAssetBundleRefs.Add (keyName, abRef);
		}
	}
 public bool Delete(AssetBundle assetBundle)
 {
     try
     {
         _ctx.AssetBundles.Remove(assetBundle);
         return true;
     }
     catch
     {
         return false;
     }
 }
 public bool Insert(AssetBundle assetBundle)
 {
     try
     {
         _ctx.AssetBundles.Add(assetBundle);
         return true;
     }
     catch
     {
         return false;
     }
 }
示例#28
0
 public static void AddBundle(string url, int version, AssetBundle bundle)
 {
     var keyName = url + version;
     if (dictAssetBundleRefs.ContainsKey(keyName))
     {
         Debug.Log(keyName + " is already loaded");
         return;
     }
     var abRef = new AssetBundleRef(url, version) {assetBundle = bundle};
     dictAssetBundleRefs.Add(keyName, abRef);
     Debug.Log(keyName + " added");
 }
 void OnAssetsLoadingComplete(AssetBundle a_assetsbundle, AssetsInfo a_assetsInfo)
 {
     TotalAssets++;
     GameObject loadedObject;
     loadedObject = Instantiate(a_assetsbundle.LoadAsset(a_assetsInfo.AssetName, typeof(GameObject))) as GameObject;
     loadedObject.SetActive(false);
     m_assetsGameObjlst.Add(loadedObject.GetComponent<AssetsData>());
     if (TotalAssets == GameManager.Instance.AllAssetsInfoList.Count)
     {
       GameState l_gameState =  FiniteStateMachine.Instance.GetCurrentState<GameState>();
         l_gameState.MakeActiveArCameraAndImageTarget(m_assetsGameObjlst);
     }
 }
	IEnumerator StartDownload (string path) 
	{
		download = new WWW (path);
		yield return download;
		
		assetBundle = download.assetBundle;

		Debug.Log ("down load: " + download.assetBundle.mainAsset.name);

		label_path.text = resourcePath + download.assetBundle.mainAsset.name + ".json";
		System.IO.File.WriteAllText(resourcePath + download.assetBundle.mainAsset.name + ".json", download.assetBundle.mainAsset.ToString());  
		count++;
		startDownloadByIdx(count);
	}
示例#31
0
        public IEnumerator LoadAssetAsync <T>(string path, UnityAction <T> callback) where T : class
        {
            string absolutepath = path;

            path = PathUtils.NormalizePath(path);


            Debug.Log("[LoadAssetAsync]: " + path);
            //打的ab包都资源名称和文件名都是小写的
            string assetBundleName = PathUtils.GetAssetBundleNameWithPath(path, assetRootPath);

            //1加载Manifest文件
            LoadManifest();
            //2获取文件依赖列表
            string[] dependencies = manifest.GetAllDependencies(assetBundleName);
            //3加载依赖资源
            AssetBundleCreateRequest createRequest;
            List <AssetBundle>       assetbundleList = new List <AssetBundle>();

            foreach (string fileName in dependencies)
            {
                string dependencyPath = assetRootPath + "/" + fileName;

                Debug.Log("[加载1 依赖资源]: " + dependencyPath);
                createRequest = AssetBundle.LoadFromFileAsync(dependencyPath);
                yield return(createRequest);

                if (createRequest.isDone)
                {
                    assetbundleList.Add(createRequest.assetBundle);
                }
                else
                {
                    Debug.Log("加载依赖资源出错");
                }
            }
            //4加载目标资源
            AssetBundle assetBundle = null;

            Debug.Log("[加载2 目标资源]: " + path);
            createRequest = AssetBundle.LoadFromFileAsync(path);
            yield return(createRequest);

            if (createRequest.isDone)
            {
                assetBundle = createRequest.assetBundle;
                //5释放目标资源
                assetbundleList.Insert(0, assetBundle);
            }
            AssetBundleRequest abr = assetBundle.LoadAssetAsync(Path.GetFileNameWithoutExtension(path), typeof(T));

            yield return(abr);

            Object obj = abr.asset;

            AssetManager.Instance.pushCache(absolutepath, obj);

            callback(obj as T);

            //yield return null;
            //yield return null;
            //6释放依赖资源
            UnloadAssetbundle(assetbundleList);
            //Debug.Log("---end loadAsync:AssetBundleLoader.loadAsync" + path);
        }
示例#32
0
    public bool LoadScene(string abName)
    {
        AssetBundle ab = LoadAssetBundle(abName);

        return(ab != null);
    }
示例#33
0
        public async ETTask LoadOneBundleAsync(string assetBundleName)
        {
            ABInfo abInfo;

            if (this.bundles.TryGetValue(assetBundleName, out abInfo))
            {
                ++abInfo.RefCount;
                return;
            }

            //Log.Debug($"---------------load one bundle {assetBundleName}");
            if (!Define.IsAsync)
            {
                string[] realPath = null;
#if UNITY_EDITOR
                realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
                foreach (string s in realPath)
                {
                    string             assetName = Path.GetFileNameWithoutExtension(s);
                    UnityEngine.Object resource  = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(s);
                    AddResource(assetBundleName, assetName, resource);
                }

                abInfo        = new ABInfo(assetBundleName, null);
                abInfo.Parent = this;
                this.bundles[assetBundleName] = abInfo;
#endif
                return;
            }

            string      p           = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
            AssetBundle assetBundle = null;
            if (!File.Exists(p))
            {
                p = Path.Combine(PathHelper.AppResPath, assetBundleName);
            }

            using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = ComponentFactory.Create <AssetsBundleLoaderAsync>())
            {
                assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
            }

            if (assetBundle == null)
            {
                throw new Exception($"assets bundle not found: {assetBundleName}");
            }

            if (!assetBundle.isStreamedSceneAssetBundle)
            {
                // 异步load资源到内存cache住
                UnityEngine.Object[] assets;
                using (AssetsLoaderAsync assetsLoaderAsync = ComponentFactory.Create <AssetsLoaderAsync, AssetBundle>(assetBundle))
                {
                    assets = await assetsLoaderAsync.LoadAllAssetsAsync();
                }
                foreach (UnityEngine.Object asset in assets)
                {
                    AddResource(assetBundleName, asset.name, asset);
                }
            }

            abInfo        = new ABInfo(assetBundleName, assetBundle);
            abInfo.Parent = this;
            this.bundles[assetBundleName] = abInfo;
        }
示例#34
0
        /// <summary>
        /// 解密Asset
        /// </summary>
        /// <param name="assetBytes"></param>
        /// <returns></returns>
        private LibraryAssetData DecryptAsset(byte[] assetBytes)
        {
            LibraryAssetData data = null;

            byte[] bt    = null;
            int    index = 0;

            // 读取文件名长度
            int assetNameLen;

            BytesUtility.GetIntFromBytes(assetBytes, out assetNameLen, ref index);
            Debug.Log("Read asset name Length=" + assetNameLen);

            // 读取文件名
            bt = new byte[assetNameLen];
            Array.Copy(assetBytes, index, bt, 0, assetNameLen);
            index += assetNameLen;

            string assetName = Encoding.UTF8.GetString(bt);

            Debug.Log("Read asset name=" + assetName);

            // 读取Asset
            // 判断是否已经加载该资源
            if (storageAssetDic.ContainsKey(assetName))
            {
                data = storageAssetDic[assetName];
                Debug.Log("Has loaded this asset!");
            }
            else
            {
                data           = new LibraryAssetData();
                data.assetName = assetName;

                // 读取文件路径长度
                int fileNameLen;
                BytesUtility.GetIntFromBytes(assetBytes, out fileNameLen, ref index);

                Debug.Log("Read asset file name Length=" + fileNameLen);

                // 读取文件路径
                bt = new byte[fileNameLen];
                Array.Copy(assetBytes, index, bt, 0, fileNameLen);
                index += fileNameLen;

                data.assetFileName = Encoding.UTF8.GetString(bt);
                Debug.Log("Read file name=" + data.assetFileName);

                // 读取Asset文件长度
                long fileLen;
                BytesUtility.GetLongFromBytes(assetBytes, out fileLen, ref index);
                Debug.Log("Read file len=" + fileLen);

                byte[] assetData = new byte[fileLen];
                Array.Copy(assetBytes, index, assetData, 0, (int)fileLen);

                data.bundle = AssetBundle.LoadFromMemory(assetData);
                Debug.Log("Read AssetBundle " + data.bundle);

                storageAssetDic.Add(data.assetName, data);
            }


            return(data);
        }
 private void OnAssetBundleComplete(AssetBundle bundle)
 {
     AssetBundle = bundle;
     Failed      = bundle == null;
     IsDone      = true;
 }
示例#36
0
    public void UpdateMapsAndMenu()
    {
        if (!Application.isEditor)
        {
            allLoadedBundles.ForEach(b => b.Unload(false));
            allLoadedBundles.Clear();
        }

        MapDropdown.ClearOptions();
        loadableSceneNames.Clear();
        MapSprites.Clear();

        int selectedMapIndex = 0;
        var selectedMapName  = PlayerPrefs.GetString("SELECTED_MAP", null);

#if UNITY_EDITOR
        if (assetBundleManager != null)
        {
            foreach (var map in assetBundleManager.assetBundleSettings.maps)
            {
                var scn = map.sceneAsset as UnityEditor.SceneAsset;
                if (scn != null)
                {
                    var sceneName = scn.name;
                    if (Application.CanStreamedLevelBeLoaded(sceneName) && !loadableSceneNames.Contains(sceneName))
                    {
                        if (sceneName == selectedMapName)
                        {
                            selectedMapIndex = loadableSceneNames.Count;
                        }
                        loadableSceneNames.Add(sceneName);
                        MapSprites.Add(map.spriteImg);
                    }
                }
            }
            MapDropdown.AddOptions(loadableSceneNames);
        }
#endif

        if (!Application.isEditor)
        {
            var bundleRoot = Path.Combine(Application.dataPath, "..", "AssetBundles");
            var files      = Directory.GetFiles(bundleRoot);
            foreach (var f in files)
            {
                if (Path.HasExtension(f))
                {
                    continue;
                }
                var filename = Path.GetFileName(f);
                if (filename.StartsWith("map_"))
                {
                    var mapName = filename.Substring("map_".Length);
                    var bundle  = AssetBundle.LoadFromFile(f); //will take long with many scenes so change to async later
                    if (bundle != null)
                    {
                        allLoadedBundles.Add(bundle);
                    }
                    string[] scenes = bundle.GetAllScenePaths(); //assume each bundle has at most one scene
                    if (scenes.Length > 0)
                    {
                        string sceneName = Path.GetFileNameWithoutExtension(scenes[0]);
                        if (sceneName == selectedMapName)
                        {
                            selectedMapIndex = loadableSceneNames.Count;
                        }
                        loadableSceneNames.Add(sceneName);
                        Sprite spriteImg        = null;
                        var    spriteBundleFile = f.Replace($"map_{mapName}", $"mapimage_{mapName}");
                        if (File.Exists(spriteBundleFile))
                        {
                            var spriteBundle = AssetBundle.LoadFromFile(spriteBundleFile);
                            if (spriteBundle != null)
                            {
                                allLoadedBundles.Add(spriteBundle);
                                spriteImg = spriteBundle.LoadAsset <Sprite>($"mapimage_{mapName}");
                            }
                        }
                        MapSprites.Add(spriteImg);
                    }
                }
            }
            MapDropdown.AddOptions(loadableSceneNames);
        }

        MapDropdown.value = selectedMapIndex;
        ChangeMapImage();
    }
        IEnumerator OnLoadAssetBundle(string abName, Type type)
        {
            string url = m_BaseDownloadingURL + abName;

            WWW download = null;

            if (type == typeof(AssetBundleManifest))
            {
                download = new WWW(url);
            }
            else
            {
                string[] dependencies = m_AssetBundleManifest.GetAllDependencies(abName);
                if (dependencies.Length > 0)
                {
                    if (!m_Dependencies.ContainsKey(abName))
                    {
                        m_Dependencies.Add(abName, dependencies);
                    }
                    for (int i = 0; i < dependencies.Length; i++)
                    {
                        string          depName    = dependencies[i];
                        AssetBundleInfo bundleInfo = null;
                        if (m_LoadedAssetBundles.TryGetValue(depName, out bundleInfo))
                        {
                            bundleInfo.m_ReferencedCount++;
                        }
                        else/* if (!m_LoadRequests.ContainsKey(depName))*/
                        {
                            yield return(StartCoroutine(OnLoadAssetBundle(depName, type)));
                        }
                    }
                }
                download = WWW.LoadFromCacheOrDownload(url, m_AssetBundleManifest.GetAssetBundleHash(abName), 0);
            }
            yield return(download);

            AssetBundle assetObj = null;

            try
            {
                assetObj = download.assetBundle;
            }
            catch (Exception)
            {
                Debug.Log("");
                throw;
            }

            if (assetObj != null)
            {
                var bundleInfo = new AssetBundleInfo(assetObj);
                m_LoadedAssetBundles.Add(abName, bundleInfo);


                List <LoadAssetRequest> list = null;
                if (!m_LoadRequests.TryGetValue(abName, out list))
                {
                    m_LoadRequests.Remove(abName);
                    yield break;
                }
                else
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i] != null)
                        {
                            string[]       assetNames = list[i].assetNames;
                            List <UObject> result     = new List <UObject>();

                            AssetBundle ab = bundleInfo.m_AssetBundle;
                            for (int j = 0; j < assetNames.Length; j++)
                            {
                                string             assetPath = assetNames[j];
                                AssetBundleRequest request   = ab.LoadAssetAsync(assetPath, list[i].assetType);
                                yield return(request);

                                result.Add(request.asset);
                                ///重置资源的shader
#if UNITY_EDITOR
                                LuaMVC.Utils_LuaMVC.ResetShader(request.asset);
#endif
                            }
                            if (list[i].sharpFunc != null)
                            {
                                StartCoroutine(DoAction(list[i].sharpFunc, result.ToArray()));
                            }
                            bundleInfo.m_ReferencedCount++;
                        }
                    }
                    m_LoadRequests.Remove(abName);
                }
            }
        }
        /// <summary>
        /// 异步加载对象
        /// </summary>
        /// <param name="abName"> Assetbundle 名称 </param>
        /// <param name="objName"> Assetbundle 中对象名称 </param>
        /// <param name="fullPath"> Assetbundle 文件路径 </param>
        /// <param name="callback"> 加载完成回调 , param1 状态码, param2 资源 </param>
        /// <returns></returns>
        private static IEnumerator AsyncLoadByKey <T>(string abName, string objName, string fullPath,
                                                      Action <int, ResBundle, ResUnit> callback = null) where T : UnityEngine.Object
        {
            if (string.IsNullOrEmpty(abName))
            {
                if (isShowDebugInfo)
                {
                    UnityEngine.Debug.Log(
                        " ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadByKey info: ab name is empty ");
                }

                yield break;
            }

            if (isShowDebugInfo)
            {
                UnityEngine.Debug.Log(
                    " ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadByKey info: ab name is " +
                    abName);
            }

            // 对象还未加载,等待加载完成
            while (_resCache != null &&
                   _resCache.ContainsKey(abName) &&
                   !_resCache[abName].ContainResUnit <T>(objName))
            {
                if (isShowDebugInfo)
                {
                    UnityEngine.Debug.Log(
                        " ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadByKey info: waiting asset " +
                        objName);
                }

                yield return(null);
            }

            ResBundle resBundle = null;

            if (_resCache != null && !_resCache.ContainsKey(abName))
            {
                if (isShowDebugInfo)
                {
                    UnityEngine.Debug.Log(
                        " ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadByKey info: new res bundle ");
                }

                resBundle = new ResBundle()
                {
                    Name = abName
                };

                _resCache.Add(abName, resBundle);
            }
            else
            {
                if (isShowDebugInfo)
                {
                    UnityEngine.Debug.Log(
                        " ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadByKey info: load from cache res bundle ");
                    UnityEngine.Debug.Log(
                        " ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadByKey info: load from cache res num " +
                        _resCache.Count);
                }

                resBundle = _resCache[abName];

                // 对象还未加载,阻塞流程
                while (resBundle.ResUnits == null ||
                       resBundle.ResUnits.Count < 0 ||
                       resBundle.ResUnits.Count > 0 && resBundle.ResUnits.Count < resBundle.ResUnitCount)
                {
                    resBundle = _resCache[abName];

                    yield return(null);
                }

                if (isShowDebugInfo)
                {
                    UnityEngine.Debug.LogWarning(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAssetByKey info: load cache obj name " + objName);
                }

                if (callback != null)
                {
                    callback(1, resBundle, resBundle.FindResUnit <T>(objName));
                }

                yield break;
            }

            /*UnityEngine.Debug.Log(
             *  " ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadByKey info: load from file bundle " +
             *  fullPath);*/

            //WWW request = WWW.LoadFromCacheOrDownload(fullPath, 1);
            AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(fullPath);

            while (!request.isDone)
            {
                ResUnit unit = resBundle.FindResUnit <T>(objName);
                if (unit != null)
                {
                    unit.Progress = request.progress;

                    Debug.Log(" load ab progress ++ " + unit.Progress);
                }

                yield return(null);
            }

            /*if ( request != null && !string.IsNullOrEmpty( request.error ) )
             * {
             *  UnityEngine.Debug.Log(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadByKey info: load from file bundle err !! " + request.error );
             * }*/

            var bundles = request.assetBundle;

            if (bundles != null)
            {
                var objs = bundles.LoadAllAssets();

                if (objs != null)
                {
                    if (isShowDebugInfo)
                    {
                        UnityEngine.Debug.Log(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAssetByKey info: total obj num  " + objs.Length);
                    }

                    for (int i = 0; i < objs.Length; ++i)
                    {
                        if (resBundle != null &&
                            !resBundle.ContainResUnit <T>(objs[i].name))
                        {
                            T resObj = objs[i] as T;

                            ResUnit u = new ResUnit()
                            {
                                ResName  = objs[i].name,
                                Progress = 1f,
                                ResObj   = (resObj == null) ? objs[i] : resObj,
                            };

                            if (u.ResObj == null)
                            {
                                UnityEngine.Debug.LogError(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAssetByKey info: cache obj error " + objs[i].name);
                            }

                            resBundle.ResAB = bundles;
                            resBundle.ResUnits.Add(u);

                            if (isShowDebugInfo)
                            {
                                UnityEngine.Debug.Log(
                                    " ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAssetByKey info: obj index " +
                                    i);

                                UnityEngine.Debug.Log(
                                    " ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAssetByKey info: obj name " +
                                    objs[i].name);
                            }

                            if (objName.Equals(objs[i].name))
                            {
                                if (isShowDebugInfo)
                                {
                                    UnityEngine.Debug.Log(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAssetByKey info: target obj type " + objs[i].GetType().Name);
                                    UnityEngine.Debug.Log(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAssetByKey info: target obj name " + objName);
                                }

                                if (callback != null)
                                {
                                    callback(1, resBundle, u);
                                }
                            }
                        }
                    }

                    if (resBundle != null)
                    {
                        resBundle.isLoaded = true;
                    }
                }
                else
                {
                    callback(0, resBundle, null);
                }

                //bundles.Unload(false);
            }
            else
            {
                callback(0, resBundle, null);
            }

            //request.Dispose();
            request = null;
        }
        /// <summary>
        /// 加载 Assetbundle 中全部对象
        /// </summary>
        /// <param name="abName"> Assetbundle 名称 </param>
        /// <param name="fullPath"> Assetbundle 文件路径 </param>
        /// <param name="callback"> 加载完成回调 , param1 状态码, param2 资源 </param>
        /// <returns></returns>
        private static IEnumerator AsyncLoadAllAssets(string abName, string fullPath, Action <int, ResUnit> callback = null)
        {
            if (string.IsNullOrEmpty(abName))
            {
                if (isShowDebugInfo)
                {
                    Debug.LogWarning(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAllAssets info: ab name is empty ");
                }

                yield break;
            }

            if (isShowDebugInfo)
            {
                Debug.Log(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAllAssets info: ab name " + abName);
            }

            // Assetbundle 未加载完成,等待加载完成
            while (_resCache != null &&
                   _resCache.ContainsKey(abName) &&
                   _resCache[abName].ResUnits.Count <= 0)
            {
                yield return(null);
            }

            ResBundle resBundle = null;

            // 首次加载 Assetbundle
            if (_resCache != null &&
                !_resCache.ContainsKey(abName))
            {
                resBundle      = new ResBundle();
                resBundle.Name = abName;

                List <ResUnit> resUnits = new List <ResUnit>();

                resBundle.ResUnits = resUnits;

                if (_resCache != null)
                {
                    _resCache.Add(abName, resBundle);
                }
            }
            else// 再次加载 Assetbundle
            {
                resBundle = _resCache[abName];

                // 对象还未加载,等待加载完成
                while ((resBundle.ResUnits.Count <= 0 ||
                        (resBundle.ResUnits.Count > 0 &&
                         resBundle.ResUnits.Count < resBundle.ResUnitCount)))
                {
                    resBundle = _resCache[abName];

                    yield return(null);
                }

                if (isShowDebugInfo)
                {
                    Debug.Log(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAllAssets info: all objs Count " + resBundle.ResUnits.Count);
                }

                //
                for (int i = 0; i < resBundle.ResUnits.Count; ++i)
                {
                    if (isShowDebugInfo)
                    {
                        Debug.Log(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAllAssets info: cache obj Name " + resBundle.ResUnits[i].ResName);
                    }

                    if (callback != null)
                    {
                        callback(1, resBundle.ResUnits[i]);
                    }

                    yield return(null);
                }

                yield break;
            }

            AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(fullPath);

            while (!request.isDone)
            {
                yield return(null);
            }

            var bundles = request.assetBundle;

            if (bundles != null)
            {
                resBundle.ResAB = bundles;

                var objs = bundles.LoadAllAssets();

                if (objs != null)
                {
                    if (resBundle != null)
                    {
                        if (isShowDebugInfo)
                        {
                            UnityEngine.Debug.Log(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAllAssets info: all objs Count " + objs.Length);
                        }

                        resBundle.ResUnitCount = objs.Length;
                    }

                    for (int i = 0; i < objs.Length; ++i)
                    {
                        if (resBundle != null &&
                            !resBundle.ContainResUnit(objs[i].name, objs[i].GetType()))
                        {
                            ResUnit unit = new ResUnit
                            {
                                ResName  = objs[i].name,
                                ResObj   = objs[i],
                                Progress = 1
                            };

                            resBundle.ResUnits.Add(unit);

                            if (isShowDebugInfo)
                            {
                                Debug.Log(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAllAssets info: load obj Type " + unit.ResObj.GetType());
                                Debug.Log(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAllAssets info: load obj Name " + unit.ResName);
                            }

                            if (callback != null)
                            {
                                callback(1, unit);
                            }
                        }
                    }

                    if (resBundle != null)
                    {
                        resBundle.isLoaded = true;
                    }
                }
                else
                {
                    if (isShowDebugInfo)
                    {
                        UnityEngine.Debug.LogWarning(" ## Uni Output ## moudule: ResManager Plugin cls:ResManager func:AsyncLoadAllAssets info: all objs Count " + resBundle.ResUnits.Count);
                    }

                    callback(0, null);
                }
            }
            else
            {
                callback(0, null);
            }
        }
示例#40
0
 /// <summary>
 /// Load an asset bundle
 /// </summary>
 /// <param name="data">The byte array</param>
 public static AssetBundle GetBundleFromBytes(byte[] data)
 {
     return(AssetBundle.LoadFromMemory(data));
 }
        /// <summary>
        /// 异步加载场景
        /// </summary>
        /// <param name="key"> 场景名称 </param>
        /// <param name="abName"> Assetbundle 名称 </param>
        /// <param name="fullPath"> Assetbundle 路径 </param>
        /// <param name="callback"> 加载完成回调 , param1 状态码, param2 资源 </param>
        /// <returns></returns>
        private static IEnumerator AsyncLoadScene(string abName, string fullPath, Action <int, GameObject[]> callback = null)
        {
            if (isShowDebugInfo)
            {
                Debug.Log(" ## Uni Output ## module:ResManagerPlugin cls:ResManager func:AsyncLoadScene info: scene assetbudnle fullPath " + fullPath);
            }

            while (_resCache != null &&
                   _resCache.ContainsKey(abName) &&
                   _resCache[abName].ResUnits.Count <= 0)
            {
                yield return(null);
            }

            ResBundle resBundle = null;

            if (_resCache != null && !_resCache.ContainsKey(abName))
            {
                resBundle = new ResBundle()
                {
                    Name = abName
                };

                ResUnit unit = new ResUnit
                {
                    ResName = abName
                };

                resBundle.ResUnits.Add(unit);

                if (isShowDebugInfo)
                {
                    Debug.Log(" ## Uni Output ## module:ResManagerPlugin cls:ResManager func:AsyncLoadScene info: load scene name " + unit.ResName);
                }

                _resCache.Add(abName, resBundle);
            }
            else
            {
                resBundle = _resCache[abName];

                while (resBundle == null ||
                       resBundle.ResUnits.Count == 0 ||
                       resBundle.ResUnits.Count > 0 && resBundle.ResUnits.Count < resBundle.ResUnitCount)
                {
                    resBundle = _resCache[abName];

                    yield return(null);
                }

                ResUnit unit = resBundle.FindResUnit(abName);

                if (isShowDebugInfo)
                {
                    Debug.Log(" ## Uni Output ## module:ResManagerPlugin cls:ResManager func:AsyncLoadScene info: load cache scene name " + unit.ResName);
                }

                if (callback != null)
                {
                    callback(0, (GameObject[])unit.ResObj);
                }

                yield break;
            }

            AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(fullPath);

            while (!request.isDone)
            {
                yield return(null);
            }

            AssetBundle bundles = request.assetBundle;

            if (bundles != null)
            {
                string[] scenePaths = bundles.GetAllScenePaths();

                if (scenePaths != null)
                {
                    if (isShowDebugInfo)
                    {
                        Debug.Log(" ## Uni Output ## module:ResManagerPlugin cls:ResManager func:AsyncLoadScene info: load scene count " + scenePaths.Length);
                    }

                    if (resBundle != null)
                    {
                        resBundle.ResAB        = bundles;
                        resBundle.ResUnitCount = scenePaths.Length;
                    }

                    for (int i = 0; i < scenePaths.Length; ++i)
                    {
                        string scenePath = scenePaths[i];

                        if (!string.IsNullOrEmpty(scenePath))
                        {
                            Scene srcScene = SceneManager.GetActiveScene();

                            AsyncOperation asyncOp = SceneManager.LoadSceneAsync(scenePath, LoadSceneMode.Additive);

                            while (!asyncOp.isDone)
                            {
                                yield return(null);
                            }

                            Scene destScene = SceneManager.GetSceneByPath(scenePath);

                            while (!destScene.isLoaded)
                            {
                                yield return(null);
                            }

                            SceneManager.MergeScenes(srcScene, destScene);

                            SceneManager.SetActiveScene(destScene);

                            ResUnit resUnit = new ResUnit
                            {
                                ResName  = scenePath,
                                Progress = 1f,
                                ResObj   = destScene.GetRootGameObjects()
                            };

                            if (resBundle != null &&
                                !resBundle.ContainResUnit(scenePath))
                            {
                                resBundle.ResUnits.Add(resUnit);
                            }

                            if (isShowDebugInfo)
                            {
                                Debug.Log(" ## Uni Output ## module:ResManagerPlugin cls:ResManager func:AsyncLoadScene info: load scene name " + resUnit.ResName);
                            }

                            if (callback != null)
                            {
                                callback(1, resUnit.ResObj as GameObject[]);
                            }
                        }
                    }

                    if (resBundle != null)
                    {
                        resBundle.isLoaded = true;
                    }
                }

                //bundles.Unload(false);
            }
        }
示例#42
0
    void OnGUI()
    {
        GUIStyle btnStyle = new GUIStyle(GUI.skin.button);

        btnStyle.alignment = TextAnchor.MiddleLeft;

        if (string.IsNullOrEmpty(m_path))
        {
            GUILayout.Label("please drag and drop a .unity3d file to this window!");
        }
        else
        {
            GUILayout.BeginHorizontal();
            GUILayout.Label(m_path);
            GUI.color = Color.red;
            if (GUILayout.Button("Export..."))
            {
                string strSaveFolder = EditorUtility.SaveFolderPanel("Export all text file from .unity3d", "", "");
                if (!string.IsNullOrEmpty(strSaveFolder))
                {
                    for (int i = 0, len = m_listObjName.Count; i < len; i++)
                    {
                        System.Type objType = m_listObjType[i];
                        string      objName = m_listObjName[i];
                        if (objType.Equals(typeof(TextAsset)))
                        {
                            TextAsset ta       = null;
                            string    fileName = null;
                            if (objName.StartsWith("en.u."))
                            {
                                fileName = objName.Substring(objName.IndexOf('.', 5) + 1);
                                ta       = m_encryptAssetBundle.LoadAsset(fileName, objType) as TextAsset;
                            }
                            else
                            {
                                fileName = objName;
                                ta       = m_assetBundle.LoadAsset(fileName, objType) as TextAsset;
                            }

                            if (ta == null)
                            {
                                EditorUtility.DisplayDialog("error", "AssetBundle not has .txt file: " + fileName, "ok");
                            }
                            else
                            {
                                if (ta.bytes != null && ta.bytes.Length > 0)
                                {
                                    System.IO.FileStream fs = System.IO.File.Create(strSaveFolder + "/" + fileName + ".bin");
                                    fs.Write(ta.bytes, 0, ta.bytes.Length);
                                    fs.Close();
                                }
                                else
                                {
                                    System.IO.StreamWriter sw = System.IO.File.CreateText(strSaveFolder + "/" + fileName + ".txt");
                                    sw.Write(ta.text);
                                    sw.Close();
                                }
                            }
                        }
                    }

                    EditorUtility.DisplayDialog("finish", "success done!", "ok");
                }
            }
            GUI.color = Color.white;
            GUILayout.EndHorizontal();
        }

        GUI.color    = Color.white;
        m_vScrollPos = EditorGUILayout.BeginScrollView(m_vScrollPos, true, true);
        for (int i = 0, len = m_listObjName.Count; i < len; i++)
        {
            System.Type objType = m_listObjType[i];
            string      objName = m_listObjName[i];

            GUILayout.BeginHorizontal();

            GUI.color = Color.white;
            GUILayout.Label(objType.ToString(), GUILayout.Width(300));

            if (objType.Equals(typeof(TextAsset)))
            {
                if (m_curViewFileName.Equals(objName))
                {
                    GUI.color = Color.yellow;
                }
                else
                {
                    GUI.color = Color.green;
                }
            }
            else
            {
                GUI.color = Color.white;
            }
            if (GUILayout.Button(objName, btnStyle))
            {
                if (objType.Equals(typeof(TextAsset)))
                {
                    if (m_curViewFileName.Equals(objName))
                    {
                        m_curViewFileName    = "";
                        m_curViewFileContent = "";
                    }
                    else
                    {
                        TextAsset ta;

                        if (objName.StartsWith("en.u."))
                        {
                            string realName = objName.Substring(objName.IndexOf('.', 5) + 1);
                            ta = m_encryptAssetBundle.LoadAsset(realName, objType) as TextAsset;
                        }
                        else
                        {
                            ta = m_assetBundle.LoadAsset(objName, objType) as TextAsset;
                        }

                        if (ta == null)
                        {
                            EditorUtility.DisplayDialog("error", "AssetBundle not has .txt file: " + objName, "ok");
                        }
                        else
                        {
                            m_curViewFileName    = objName;
                            m_curViewFileContent = ta.text;
                        }
                    }
                }
            }

            GUILayout.EndHorizontal();

            if (m_curViewFileName.Equals(objName))
            {
                GUI.color = Color.white;
                GUILayout.TextArea(m_curViewFileContent, GUILayout.Width(10000f));
            }
        }
        EditorGUILayout.EndScrollView();

        DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
        if (Event.current.type == EventType.DragExited)
        {
            int len = DragAndDrop.paths.Length;
            if (len == 0)
            {
                EditorUtility.DisplayDialog("error", "please drag and drop a .unity3d file to this window!", "ok");
            }
            else
            {
                m_path = DragAndDrop.paths[0];

                clear();

                m_assetBundle = AssetBundle.LoadFromMemory(System.IO.File.ReadAllBytes(m_path));

                if (m_assetBundle != null)
                {
                    foreach (Object obj in m_assetBundle.LoadAllAssets())
                    {
                        if (obj.name.StartsWith("en.u.") && obj.GetType() == typeof(TextAsset))
                        {
                            TextAsset ta = obj as TextAsset;

                            //byte[] bytes = global.DecryptBytes(ta.bytes, global.EncryptAssetBundleKey);

                            m_encryptAssetBundle = AssetBundle.LoadFromMemory(ta.bytes);

                            foreach (Object obj2 in m_encryptAssetBundle.LoadAllAssets())
                            {
                                m_listObjType.Add(obj2.GetType());
                                m_listObjName.Add(obj.name + "." + obj2.name);
                            }
                        }
                        else
                        {
                            m_listObjType.Add(obj.GetType());
                            m_listObjName.Add(obj.name);
                        }
                    }
                }
            }
        }
    }
示例#43
0
        private void LoadOneBundle(string assetBundleName)
        {
            assetBundleName = assetBundleName.BundleNameToLower();
            ABInfo abInfo;
            if (this.bundles.TryGetValue(assetBundleName, out abInfo))
            {
                ++abInfo.RefCount;
                //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
                return;
            }
            
            if (!Define.IsAsync)
            {
                string[] realPath = null;
#if UNITY_EDITOR
                realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
                foreach (string s in realPath)
                {
                    string assetName = Path.GetFileNameWithoutExtension(s);
                    UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
                    AddResource(assetBundleName, assetName, resource);
                }

            
              
                if (realPath.Length > 0)
                {
                    abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
                    this.bundles[assetBundleName] = abInfo;
                    //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
                }
                else
                {
                    Log.Error($"assets bundle not found: {assetBundleName}");
                }
#endif
                return;
            }

            string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
            AssetBundle assetBundle = null;
            if (File.Exists(p))
            {
                assetBundle = AssetBundle.LoadFromFile(p);
            }
            else
            {
                p = Path.Combine(PathHelper.AppResPath, assetBundleName);
                assetBundle = AssetBundle.LoadFromFile(p);
            }

            if (assetBundle == null)
            {
                // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
                Log.Warning($"assets bundle not found: {assetBundleName}");
                return;
            }

            if (!assetBundle.isStreamedSceneAssetBundle)
            {
                // 异步load资源到内存cache住
                UnityEngine.Object[] assets = assetBundle.LoadAllAssets();
                foreach (UnityEngine.Object asset in assets)
                {
                    AddResource(assetBundleName, asset.name, asset);
                }
            }

            abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
            this.bundles[assetBundleName] = abInfo;
            
            //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
        }
示例#44
0
        private async ETTask LoadOneBundleAsync(string assetBundleName, bool isScene)
        {
            assetBundleName = assetBundleName.BundleNameToLower();
            ABInfo abInfo;
            if (this.bundles.TryGetValue(assetBundleName, out abInfo))
            {
                ++abInfo.RefCount;
                //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
                return;
            }

            string p = "";
            AssetBundle assetBundle = null;
            
            if (!Define.IsAsync)
            {
#if UNITY_EDITOR

                if (isScene)
                {
                    p = Path.Combine(Application.dataPath, "../SceneBundle/", assetBundleName);
                    if (File.Exists(p)) // 如果场景有预先打包
                    {
                        using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = EntityFactory.CreateWithParent<AssetsBundleLoaderAsync>(this))
                        {
                            assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
                        }

                        if (assetBundle == null)
                        {
                            // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
                            Log.Warning($"Scene bundle not found: {assetBundleName}");
                            return;
                        }
                        
                        abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
                        this.bundles[assetBundleName] = abInfo;
                    }
                }
                else
                {
                    string[] realPath = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
                    foreach (string s in realPath)
                    {
                        string assetName = Path.GetFileNameWithoutExtension(s);
                        UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(s);
                        AddResource(assetBundleName, assetName, resource);
                    }

                    if (realPath.Length > 0)
                    {
                        abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, null);
                        this.bundles[assetBundleName] = abInfo;
                        //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
                    }
                    else
                    {
                        Log.Error("Bundle not exist! BundleName: " + assetBundleName);
                    }
                }
                // 编辑器模式也不能同步加载
                await TimerComponent.Instance.WaitAsync(20);
#endif
                return;
            }

            
            p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
            if (!File.Exists(p))
            {
                p = Path.Combine(PathHelper.AppResPath, assetBundleName);
            }

            if (!File.Exists(p))
            {
                Log.Error("Async load bundle not exist! BundleName : " + p);
                return;
            }

            using (AssetsBundleLoaderAsync assetsBundleLoaderAsync = EntityFactory.CreateWithParent<AssetsBundleLoaderAsync>(this))
            {
                assetBundle = await assetsBundleLoaderAsync.LoadAsync(p);
            }

            if (assetBundle == null)
            {
                // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
                Log.Warning($"assets bundle not found: {assetBundleName}");
                return;
            }

            if (!assetBundle.isStreamedSceneAssetBundle)
            {
                // 异步load资源到内存cache住
                UnityEngine.Object[] assets;
                using (AssetsLoaderAsync assetsLoaderAsync = EntityFactory.CreateWithParent<AssetsLoaderAsync, AssetBundle>(this, assetBundle))
                {
                    assets = await assetsLoaderAsync.LoadAllAssetsAsync();
                }

                foreach (UnityEngine.Object asset in assets)
                {
                    AddResource(assetBundleName, asset.name, asset);
                }
            }

            abInfo = EntityFactory.CreateWithParent<ABInfo, string, AssetBundle>(this, assetBundleName, assetBundle);
            this.bundles[assetBundleName] = abInfo;
            
            //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
        }
示例#45
0
        //异步加载资源
        private IEnumerator LoadAssetAsync <T>(ResourceInfoBase info, HTFAction <float> loadingAction, HTFAction <T> loadDoneAction, bool isPrefab = false, Transform parent = null, bool isUI = false) where T : UnityEngine.Object
        {
            DateTime beginTime = DateTime.Now;

            if (_isLoading)
            {
                yield return(_loadWait);
            }

            _isLoading = true;

            yield return(Main.Current.StartCoroutine(LoadDependenciesAssetBundleAsync(info.AssetBundleName)));

            DateTime waitTime = DateTime.Now;

            UnityEngine.Object asset = null;

            if (Mode == ResourceLoadMode.Resource)
            {
                ResourceRequest request = Resources.LoadAsync <T>(info.ResourcePath);
                while (!request.isDone)
                {
                    loadingAction?.Invoke(request.progress);
                    yield return(null);
                }
                asset = request.asset;
                if (asset)
                {
                    if (isPrefab)
                    {
                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                    }
                }
                else
                {
                    throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:Resources文件夹中不存在资源 " + info.ResourcePath + "!");
                }
            }
            else
            {
#if UNITY_EDITOR
                if (IsEditorMode)
                {
                    loadingAction?.Invoke(1);
                    yield return(null);

                    asset = AssetDatabase.LoadAssetAtPath <T>(info.AssetPath);
                    if (asset)
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                    else
                    {
                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:路径中不存在资源 " + info.AssetPath + "!");
                    }
                }
                else
                {
                    if (_assetBundles.ContainsKey(info.AssetBundleName))
                    {
                        loadingAction?.Invoke(1);
                        yield return(null);

                        asset = _assetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                        if (asset)
                        {
                            if (isPrefab)
                            {
                                asset = ClonePrefab(asset as GameObject, parent, isUI);
                            }
                        }
                        else
                        {
                            throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                        }
                    }
                    else
                    {
                        using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(_assetBundleRootPath + info.AssetBundleName, GetAssetBundleHash(info.AssetBundleName)))
                        {
                            request.SendWebRequest();
                            while (!request.isDone)
                            {
                                loadingAction?.Invoke(request.downloadProgress);
                                yield return(null);
                            }
                            if (!request.isNetworkError && !request.isHttpError)
                            {
                                AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
                                if (bundle)
                                {
                                    asset = bundle.LoadAsset <T>(info.AssetPath);
                                    if (asset)
                                    {
                                        if (isPrefab)
                                        {
                                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                                        }
                                    }
                                    else
                                    {
                                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                                    }

                                    if (IsCacheAssetBundle)
                                    {
                                        if (!_assetBundles.ContainsKey(info.AssetBundleName))
                                        {
                                            _assetBundles.Add(info.AssetBundleName, bundle);
                                        }
                                    }
                                    else
                                    {
                                        bundle.Unload(false);
                                    }
                                }
                                else
                                {
                                    throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!");
                                }
                            }
                            else
                            {
                                throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!");
                            }
                        }
                    }
                }
#else
                if (_assetBundles.ContainsKey(info.AssetBundleName))
                {
                    loadingAction?.Invoke(1);
                    yield return(null);

                    asset = _assetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                    if (asset)
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                    else
                    {
                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                    }
                }
                else
                {
                    using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(_assetBundleRootPath + info.AssetBundleName, GetAssetBundleHash(info.AssetBundleName)))
                    {
                        request.SendWebRequest();
                        while (!request.isDone)
                        {
                            loadingAction?.Invoke(request.downloadProgress);
                            yield return(null);
                        }
                        if (!request.isNetworkError && !request.isHttpError)
                        {
                            AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
                            if (bundle)
                            {
                                asset = bundle.LoadAsset <T>(info.AssetPath);
                                if (asset)
                                {
                                    if (isPrefab)
                                    {
                                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                                    }
                                }
                                else
                                {
                                    throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                                }

                                if (IsCacheAssetBundle)
                                {
                                    if (!_assetBundles.ContainsKey(info.AssetBundleName))
                                    {
                                        _assetBundles.Add(info.AssetBundleName, bundle);
                                    }
                                }
                                else
                                {
                                    bundle.Unload(false);
                                }
                            }
                            else
                            {
                                throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!");
                            }
                        }
                        else
                        {
                            throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!");
                        }
                    }
                }
#endif
            }

            DateTime endTime = DateTime.Now;

            GlobalTools.LogInfo(string.Format("异步加载资源{0}[{1}模式]:\r\n{2}\r\n等待耗时:{3}秒  加载耗时:{4}秒", asset ? "成功" : "失败", Mode
                                              , Mode == ResourceLoadMode.Resource ? info.GetResourceFullPath() : info.GetAssetBundleFullPath(_assetBundleRootPath)
                                              , (waitTime - beginTime).TotalSeconds, (endTime - waitTime).TotalSeconds));

            if (asset)
            {
                DataSetInfo dataSet = info as DataSetInfo;
                if (dataSet != null && dataSet.Data != null)
                {
                    asset.Cast <DataSetBase>().Fill(dataSet.Data);
                }

                loadDoneAction?.Invoke(asset as T);
            }
            asset = null;

            _isLoading = false;
        }
示例#46
0
        public T GetWebAssetSync <T>(string name, Guid id) where T : UnityEngine.Object
        {
            _log.Info($"Loading asset syncronously:{name},{id}");

            string hash = GetBundleHash(id);

            hash = hash.Substring(1, hash.Length - 2);
            _log.Info("Bundle hash:" + hash);

            int type = GetBundleType(id);

            if (type == -1)
            {
                _log.Info($"Wrong bundle type for {id}");
                return(null);
            }

            if (type == 1)
            {
                if (_loadedBundles.ContainsKey(id))
                {
                    _log.Info("Found in loaded bundles");
                    var cbnd = _loadedBundles[id];



                    T cret = cbnd.LoadAsset <T>(name);

                    return(cret);
                }
                _log.Info("Loading bundle");

                //try to get from file cache
                byte[] fbytes = RootComponents.Instance.MainAssetCache.LoadAsset(hash);
                if (fbytes != null)
                {
                    AssetBundle bnd = AssetBundle.LoadFromMemory(fbytes);
                    if (bnd == null)
                    {
                        _log.Warn($"Failed to load asset bundle with id {id}, trying to get asset: {name}");

                        return(null);
                    }
                    _loadedBundles.Add(id, bnd);
                    T ret = bnd.LoadAsset <T>(name);

                    return(ret);
                }
                else
                {
                    byte[] bbytes =
                        GetURLContents(Test.Instance.MainSettings.WebApiUrl + "assets/bundle/" + id.ToString());
                    // Debug.Log("__DOWNLOADED"+bbytes.Length);
                    _log.Info("Bundle obtained");

                    RootComponents.Instance.MainAssetCache.SaveAsset(hash, Guid.NewGuid().ToString(), bbytes);

                    AssetBundle bnd = AssetBundle.LoadFromMemory(bbytes);
                    if (bnd == null)
                    {
                        _log.Warn($"Failed to load asset bundle with id {id}, trying to get asset: {name}");

                        return(null);
                    }

                    _loadedBundles.Add(id, bnd);
                    T ret = bnd.LoadAsset <T>(name);

                    return(ret);
                }
            }
            else
            {
                _log.Info($"TODO: unsupported bundle type {type}");
                return(null);
            }
        }
示例#47
0
 /// <summary xml:lang="en">
 /// Loads the effect from AssetBundle
 /// </summary>
 /// <param name="name" xml:lang="en">Effect name (that resolved extensions from efk file name)</param>
 /// <param name="assetBundle" xml:lang="en">Source AssetBundle</param>
 /// <summary xml:lang="ja">
 /// エフェクトのロード (AssetBundleから)
 /// </summary>
 /// <param name="name" xml:lang="ja">エフェクト名 (efkファイルの名前から".efk"を取り除いたもの)</param>
 /// <param name="assetBundle" xml:lang="ja">ロード元のAssetBundle</param>
 public static void LoadEffect(string name, AssetBundle assetBundle)
 {
     Instance._LoadEffect(name, assetBundle);
 }
示例#48
0
        public async Task <string> LoadSceneFromWebAsync(Guid bundleId, string sceneName)
        {
            _log.Info($"Loading scene asyncronously:{sceneName},{bundleId}");

            string hash = GetBundleHash(bundleId);


            hash = hash.Substring(1, hash.Length - 2);
            _log.Info("Bundle hash:" + hash);
            if (_loadedBundles.ContainsKey(bundleId))
            {
                _log.Info("Found in loaded bundles");
                var cbnd = _loadedBundles[bundleId];



                string[] scenePaths = cbnd.GetAllScenePaths();



                return(scenePaths[0]);
            }
            else
            {
                //try to get from file cache
                byte[] fbytes = RootComponents.Instance.MainAssetCache.LoadAsset(hash);

                if (fbytes != null)
                {
                    AssetBundle bnd = await AssetBundle.LoadFromMemoryAsync(fbytes);

                    if (bnd == null)
                    {
                        _log.Warn($"Failed to load scene bundle with id {bundleId}, trying to get scene: {sceneName}");

                        return(String.Empty);
                    }
                    _loadedBundles.Add(bundleId, bnd);

                    string[] scenePaths = bnd.GetAllScenePaths();

                    _log.Info($"Loaded scene {sceneName} from cache");

                    return(scenePaths[0]);
                }
                else
                {
                    _log.Info("Loading bundle");

                    byte[] bbytes =
                        await  GetURLContentsAsync(Test.Instance.MainSettings.WebApiUrl + "assets/bundle/" + bundleId.ToString());

                    // string dhash = _md5.ComputeHash(bbytes).ToHex(false);
                    //   _log.Info($"Downloaded hash:" + dhash);
                    RootComponents.Instance.MainAssetCache.SaveAsset(hash, Guid.NewGuid().ToString(), bbytes);

                    AssetBundle bnd = await AssetBundle.LoadFromMemoryAsync(bbytes);

                    if (bnd == null)
                    {
                        _log.Warn($"Failed to load scene bundle with id {bundleId}, trying to get scene: {sceneName}");

                        return(String.Empty);
                    }
                    _loadedBundles.Add(bundleId, bnd);

                    string[] scenePaths = bnd.GetAllScenePaths();



                    return(scenePaths[0]);
                }
            }
        }
示例#49
0
    public void Update()
    {
        if (nowData == null)
        {
            if (waitings.Count == 0)
            {
                return;
            }
            nowData = waitings[0];

            //查找是否已经加载
            if (loadedDic.ContainsKey(nowData.assetPath))
            {
                if (nowData.callback != null)
                {
                    //Debug.LogError("wtf.");
                    //nowData.callback(loadedDic[nowData.assetPath].go, nowData.param);
                    request         = loadedDic[nowData.assetPath].request;
                    nowData.request = request;
                }
                else
                {
                    waitings.RemoveAt(0);
                    nowData = null;
                }
                return;
            }

            //find depend
            string[] str = abmf.GetAllDependencies(nowData.assetPath);
            if (str == null || str.Length == 0)
            {
                //没有依赖,直接加载本资源
                string path = streammingPath + nowData.assetPath;
                request         = AssetBundle.LoadFromFileAsync(path.ToLower());
                nowData.request = request;
            }
            else
            {
                //有依赖,把依赖加入队首
                bool flag = false;
                for (int i = 0; i < str.Length; ++i)
                {
                    if (loadedDic.ContainsKey(str[i]) == true)
                    {
                        continue;
                    }
                    flag = true;
                    LoaderData data = new LoaderData();
                    data.assetPath = str[i];
                    int t = data.assetPath.LastIndexOf("/");
                    data.assetName = data.assetPath.Substring(t + 1, data.assetPath.Length - t - 1);
                    waitings.Insert(0, data);
                }
                if (flag == false)
                {
                    string path = streammingPath + nowData.assetPath;
                    request         = AssetBundle.LoadFromFileAsync(path.ToLower());
                    nowData.request = request;
                }
                else
                {
                    nowData = null;
                    return;
                }
            }
        }

        if (request != null && request.isDone == true && abrequest == null)
        {
            if (nowData.callback == null)
            {
                loadedDic[nowData.assetPath] = nowData;
                abrequest = null;
                request   = null;
                nowData   = null;
                this.waitings.RemoveAt(0);
            }
            else
            {
                abrequest = request.assetBundle.LoadAssetAsync(nowData.assetName, typeof(GameObject));
            }
        }

        if (request != null && request.isDone == true && abrequest != null && abrequest.isDone == true)
        {
            if (nowData.callback != null)
            {
                nowData.callback(abrequest.asset as GameObject, nowData.param);
            }

            loadedDic[nowData.assetPath] = nowData;

            abrequest = null;
            request   = null;
            nowData   = null;
            this.waitings.RemoveAt(0);
        }
    }
示例#50
0
        public static List <SensorBase> LoadSensorPlugins()
        {
            AssetBundle.UnloadAllAssetBundles(false);
            List <SensorBase> prefabs = RuntimeSettings.Instance.SensorPrefabs.ToList();

            if (prefabs.Any(s => s == null))
            {
                Debug.LogError("Null Sensor Prefab Detected - Check RuntimeSettings SensorPrefabs List for missing Sensor Prefab");
#if UNITY_EDITOR
                UnityEditor.EditorApplication.isPlaying = false;
#else
                // return non-zero exit code
                Application.Quit(1);
#endif
                return(null);
            }

            var sensorDirectory = Path.Combine(Application.dataPath, "..", "AssetBundles", "Sensors");
            if (Directory.Exists(sensorDirectory))
            {
                DirectoryInfo dir = new DirectoryInfo(sensorDirectory);
                foreach (FileInfo file in dir.GetFiles())
                {
                    try
                    {
                        var path = file.FullName;
                        using (ZipFile zip = new ZipFile(path))
                        {
                            string   manfile  = Encoding.UTF8.GetString(GetFile(zip, "manifest"));
                            Manifest manifest = new Deserializer().Deserialize <Manifest>(manfile);
                            Debug.Log($"Loading {manifest.assetName}");
                            if (manifest.bundleFormat != BundleConfig.SensorBundleFormatVersion)
                            {
                                throw new Exception("BundleFormat version mismatch");
                            }

                            Assembly pluginSource = Assembly.Load(GetFile(zip, $"{manifest.assetName}.dll"));
                            foreach (Type ty in pluginSource.GetTypes())
                            {
                                Type interfaceType = ty.GetInterfaces().FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IDataConverter <>));
                                if (interfaceType != null)
                                {
                                    Type converterType = interfaceType.GetGenericArguments()[0];
                                    if (!BridgeConfig.bridgeConverters.ContainsKey(converterType))
                                    {
                                        var instance = Activator.CreateInstance(ty);
                                        BridgeConfig.bridgeConverters.Add(converterType, instance as IDataConverter);
                                    }
                                }
                            }

                            string      platform     = SystemInfo.operatingSystemFamily == OperatingSystemFamily.Windows ? "windows" : "linux";
                            var         pluginStream = zip.GetInputStream(zip.GetEntry($"{manifest.assetGuid}_sensor_main_{platform}"));
                            AssetBundle pluginBundle = AssetBundle.LoadFromStream(pluginStream);
                            var         pluginAssets = pluginBundle.GetAllAssetNames();
                            prefabs.Add(pluginBundle.LoadAsset <GameObject>(pluginAssets[0]).GetComponent <SensorBase>());
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.LogException(ex);
                        Debug.LogError($"Failed to load sensor plugin {file.FullName}, skipping it.");
                    }
                }
            }

            return(prefabs);
        }
 public AssetBundleInfo(AssetBundle assetBundle)
 {
     m_AssetBundle     = assetBundle;
     m_ReferencedCount = 0;
 }
示例#52
0
    private IEnumerator GetAssetBundle()
    {
        /*//if current version is lower
         * var version = PlayerPrefs.GetString("Version", "99");
         #if UNITY_EDITOR
         * PlayerPrefs.DeleteAll();
         * version = "99";
         #endif
         *
         * UnityWebRequest www = UnityWebRequest.Get(hNetworkManager.serverURL + "/levelasset/" + version);
         * yield return www.SendWebRequest();
         *
         * if (www.isNetworkError || www.isHttpError)
         * {
         *  Application.Quit();
         * }
         * else
         * {
         *  string assetBundleDirectory = Application.persistentDataPath + "/AssetBundle";
         *  string serialDataPath = Application.persistentDataPath + "/SerialData";
         *
         *  // 에셋 번들을 저장할 경로의 폴더가 존재하지 않는다면 생성시킨다.
         *  if (!Directory.Exists(assetBundleDirectory))
         *      Directory.CreateDirectory(assetBundleDirectory);
         *  if (!Directory.Exists(serialDataPath))
         *      Directory.CreateDirectory(serialDataPath);*/

        AssetBundle assetBundle;

        hLevel[]     levelDatas;
        GameObject[] assets;
        Material[]   mats;

        /*if (www.downloadHandler.data.Length == 0)
         * {*/
#if UNITY_EDITOR
        assetBundle = AssetBundle.LoadFromFile("C:/Users/HURJM/Desktop/work/Unity/ProjectDelta(URP)/AssetBundles/StandaloneWindows/levels.unity3d");
#else
        assetBundle = AssetBundle.LoadFromFile("levels.unity3d");
#endif
        if (assetBundle == null)
        {
            //Debug.Log("Failed to load AssetBundle!");
            yield break;
        }

        mats = assetBundle.LoadAllAssets <Material>();
        for (int i = 0; i < mats.Length; ++i)
        {
            var mat = mats[i];
            mat.shader = Shader.Find(mat.shader.name);
            if (mat.name.Contains("Ground"))
            {
                hDatabase.current.groundMats.Add(mat);
            }
        }

        //binary 파일은 textasset으로 저장하고 불러옴
        assets     = assetBundle.LoadAllAssets <GameObject>();
        levelDatas = new hLevel[assets.Length];
        for (int i = 0; i < assets.Length; ++i)
        {
            levelDatas[i] = assets[i].GetComponent <hLevel>();
        }

        hSharedData.Initialize(levelDatas);
        _loading.FirstLoading();
        yield break;

        /*}
         *
         * var studio = Instantiate(m_thumbnailStudio);
         *
         * string lastVersion = "";
         * int head = 0;
         * for (; head < www.downloadHandler.data.Length; ++head)
         * {
         *  if ((char)www.downloadHandler.data[head] == '?')
         *  {
         *      PlayerPrefs.SetString("Version", lastVersion);
         ++head;
         *      break;
         *  }
         *  lastVersion += (char)www.downloadHandler.data[head];
         * }
         *
         * byte[] data = new byte[www.downloadHandler.data.Length - head];
         * System.Array.Copy(www.downloadHandler.data, head, data, 0, data.Length);
         *
         * // 파일 입출력을 통해 받아온 에셋을 저장하는 과정
         * File.WriteAllBytes(Path.Combine(assetBundleDirectory, "levels.unity3d"), data);
         *
         * assetBundle = AssetBundle.LoadFromFile(Path.Combine(assetBundleDirectory, "levels.unity3d"));
         *
         * if (assetBundle == null)
         * {
         *  //Debug.Log("Failed to load AssetBundle!");
         *  yield break;
         * }
         *
         * //binary 파일은 textasset으로 저장하고 불러옴
         * mats = assetBundle.LoadAllAssets<Material>();
         * for (int i = 0; i < mats.Length; ++i)
         * {
         *  var mat = mats[i];
         *  mat.shader = Shader.Find(mat.shader.name);
         *  if (mat.name.Contains("Ground"))
         *      hDatabase.current.groundMats.Add(mat);
         * }
         *
         * assets = assetBundle.LoadAllAssets<GameObject>();
         * levelDatas = new hLevel[assets.Length];
         * for (int i = 0; i < assets.Length; ++i)
         *  levelDatas[i] = assets[i].GetComponent<hLevel>();
         *
         * var lastThemeColor = hColorManager.current.curColor;
         * for (int i = 0; i < levelDatas.Length; ++i)
         *  studio.SaveThumbnail(levelDatas[i]);
         *
         * hColorManager.current.SetTheme(lastThemeColor, true);
         * hSharedData.Initialize(levelDatas);
         * _loading.FirstLoading();*/

        #region Binary Asset

        /*TextAsset[] textAssets;
         * AssetBundle assetBundle;
         * hLevel.SerialData[] serialDatas;
         * MemoryStream memoryStream;
         * BinaryFormatter formatter;
         *
         * if (www.downloadHandler.data.Length == 0)
         * {
         *  assetBundle = AssetBundle.LoadFromFile(Path.Combine(assetBundleDirectory, "levels.unity3d"));
         *  if (assetBundle == null)
         *  {
         *      //Debug.Log("Failed to load AssetBundle!");
         *      yield break;
         *  }
         *  else
         *      //Debug.Log("Successed to load AssetBundle!");
         *
         *  //binary 파일은 textasset으로 저장하고 불러옴
         *  textAssets = assetBundle.LoadAllAssets<TextAsset>();
         *  serialDatas = new hLevel.SerialData[textAssets.Length];
         *
         *  memoryStream = new MemoryStream();
         *  formatter = new BinaryFormatter();
         *  for (int i = 0; i < textAssets.Length; ++i)
         *  {
         *      memoryStream.Write(textAssets[i].bytes, 0, textAssets[i].bytes.Length);
         *      memoryStream.Position = 0;
         *      serialDatas[i] = (hLevel.SerialData)formatter.Deserialize(memoryStream);
         *      memoryStream.SetLength(0);
         *  }
         *  memoryStream.Close();
         *
         *  hSharedData.Initialize(serialDatas);
         *  _loading.FirstLoading();
         *  yield break;
         * }
         *
         * var studio = Instantiate(m_thumbnailStudio);
         *
         * string lastVersion = "";
         * int head = 0;
         * for (; head < www.downloadHandler.data.Length; ++head)
         * {
         *  if((char)www.downloadHandler.data[head] == '?')
         *  {
         *      PlayerPrefs.SetString("Version", lastVersion);
         ++head;
         *      break;
         *  }
         *  lastVersion += (char)www.downloadHandler.data[head];
         * }
         *
         * byte[] data = new byte[www.downloadHandler.data.Length - head];
         * System.Array.Copy(www.downloadHandler.data, head, data, 0, data.Length);
         *
         * // 파일 입출력을 통해 받아온 에셋을 저장하는 과정
         * File.WriteAllBytes(Path.Combine(assetBundleDirectory , "levels.unity3d"), data);
         *
         * assetBundle = AssetBundle.LoadFromFile(Path.Combine(assetBundleDirectory, "levels.unity3d"));
         *
         * if (assetBundle == null)
         * {
         *  //Debug.Log("Failed to load AssetBundle!");
         *  yield break;
         * }
         * else
         *  //Debug.Log("Successed to load AssetBundle!");
         *
         * //binary 파일은 textasset으로 저장하고 불러옴
         * textAssets = assetBundle.LoadAllAssets<TextAsset>();
         *
         * serialDatas = new hLevel.SerialData[textAssets.Length];
         *
         * memoryStream = new MemoryStream();
         * formatter = new BinaryFormatter();
         * for (int i = 0; i < textAssets.Length; ++i)
         * {
         *  memoryStream.Write(textAssets[i].bytes, 0, textAssets[i].bytes.Length);
         *  memoryStream.Position = 0;
         *  serialDatas[i] = (hLevel.SerialData)formatter.Deserialize(memoryStream);
         *  memoryStream.SetLength(0);
         * }
         * memoryStream.Close();
         *
         * var lastThemeColor = hColorManager.current.curColor;
         * for (int i = 0; i < serialDatas.Length; ++i)
         *  studio.SaveThumbnail(serialDatas[i]);
         * hColorManager.current.SetTheme(lastThemeColor, true);
         * hSharedData.Initialize(serialDatas);
         * _loading.FirstLoading();*/
        #endregion
    }
 private void OnAssetBundleManifestComplete(AssetBundle bundle)
 {
     Success = bundle != null;
     IsDone  = true;
 }
示例#54
0
    // Update is called once per frame
    void Update()
    {
        float startX = cameraTransform.position.x * 100 - cameraSize.x / 2 - 256;
        float endX   = cameraTransform.position.x * 100 + cameraSize.x / 2 + 256;
        float startY = cameraTransform.position.y * 100 - cameraSize.y / 2 - 256;
        float endY   = cameraTransform.position.y * 100 + cameraSize.y / 2 + 256;
        List <BackgroundPiece> piecesToShow = collection.FindWithin(startX, endX, startY, endY);
        List <BackgroundPiece> piecesToLoad = collection.FindWithin(startX - 256, endX + 256, startY - 256, endY + 256);

        foreach (BackgroundPiece piece in collection.collection)
        {
            if (!piecesToLoad.Contains(piece))
            {
                piece.shown   = false;
                piece.loading = false;
            }
        }
        ReuseOutsight();

        foreach (BackgroundPiece piece in piecesToLoad)
        {
            if (piece.shown != true)
            {
                if (piecesToShow.Contains(piece) && !piece.loading)
                {
                    var bundle = AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/background/backgroundsplit-" + piece.x + "-" + piece.y + ".normal");
                    if (bundle == null)
                    {
                        Debug.Log("Fail to Load Bundle");
                        return;
                    }
                    piece.loading = true;
                    var        backgroundTexture = bundle.LoadAsset <Texture2D>(piece.resName);
                    Sprite     sprite            = Sprite.Create(backgroundTexture, new Rect(0, 0, backgroundTexture.width, backgroundTexture.height), new Vector2(0.5f, 0.5f));
                    GameObject backgroundObject  = availableBackground.Pop();
                    backgroundObject.GetComponent <SpriteRenderer>().sprite = sprite;

                    float initPosX = piece.initialX / 100.0f;
                    int   xCount   = Mathf.FloorToInt(cameraTransform.position.x * 100 / backgroundWidth);
                    initPosX = initPosX + backgroundWidth / 100.0f * xCount;
                    if (initPosX < cameraTransform.position.x - cameraSize.x / 100.0f)
                    {
                        initPosX += backgroundWidth / 100.0f;
                    }
                    if (initPosX > cameraTransform.position.x + cameraSize.x / 100.0f)
                    {
                        initPosX -= backgroundWidth / 100.0f;
                    }
                    backgroundObject.transform.position = new Vector3(initPosX, piece.initialY / 100.0f, 0);
                    bundle.Unload(false);
                    piece.shown = true;
                }
                else
                {
                    if (!piece.loading)
                    {
                        StartCoroutine(LoadBackgroundAsync(piece));
                    }
                }
            }
        }
    }
示例#55
0
 public virtual void Decorate(GameObject go, GameObject hider, ParkitectObj parkitectObj, AssetBundle bundle)
 {
 }
示例#56
0
 public LoadedAssetBundle(AssetBundle assetBundle)
 {
     m_AssetBundle     = assetBundle;
     m_ReferencedCount = 1;
 }
示例#57
0
 public void AddSearchBundle(string name, AssetBundle bundle)
 {
     zipMap[name] = bundle;
 }
示例#58
0
    void InstanceSpineGo()
    {
        UnityEngine.Profiling.Profiler.BeginSample("MyPieceOfCode 111");
        Debug.Log("111111111");
        UnityEngine.Profiling.Profiler.EndSample();

        LoadSceneMgr loadSceneMgr = GameObject.FindObjectOfType <LoadSceneMgr>();

        Canvas            canvas          = GameObject.FindObjectOfType <Canvas>();
        AssetBundle       ab              = null;
        float             preTime         = 0.0f;
        string            prefabAssetPath = "";
        Object            prefab          = null;
        GameObject        go;
        List <GameObject> goList = new List <GameObject>();

        preTime         = Time.realtimeSinceStartup;
        ab              = loadSceneMgr.LoadBundle("binary_SkeletonGraphic");
        prefabAssetPath = "Assets/res/Prefabs/binary_SkeletonGraphic.prefab";
        prefab          = ab.LoadAsset <Object>(prefabAssetPath);
        Debug.Log(string.Format(" {0} Load Bundle Time : {1} ", "binary_SkeletonGraphic",
                                Time.realtimeSinceStartup - preTime));


        preTime = Time.realtimeSinceStartup;
        go      = Instantiate(prefab) as GameObject;

        Debug.Log(string.Format(" {0} Instantiate Time : {1} ", "binary_SkeletonGraphic",
                                Time.realtimeSinceStartup - preTime));

        go.transform.SetParent(canvas.transform, false);


        UnityEngine.Profiling.Profiler.BeginSample("MyPieceOfCode 222");
        Debug.Log("222222");
        UnityEngine.Profiling.Profiler.EndSample();

        /*
         * LoadSceneMgr loadSceneMgr = GameObject.FindObjectOfType<LoadSceneMgr>();
         *
         * Canvas canvas = GameObject.FindObjectOfType<Canvas>();
         * AssetBundle ab = null;
         * float preTime = 0.0f;
         * string prefabAssetPath = "";
         * Object prefab = null;
         * GameObject go;
         * List<GameObject> goList = new List<GameObject>();
         *
         *
         * preTime = Time.realtimeSinceStartup;
         * ab = loadSceneMgr.LoadBundle("binary_SkeletonGraphic");
         * prefabAssetPath = "Assets/res/Prefabs/binary_SkeletonGraphic.prefab";
         * prefab = ab.LoadAsset<Object>(prefabAssetPath);
         * Debug.Log(string.Format(" {0} Load Bundle Time : {1} ", "binary_SkeletonGraphic",
         *  Time.realtimeSinceStartup - preTime));
         *
         *
         * preTime = Time.realtimeSinceStartup;
         * go = Instantiate(prefab) as GameObject;
         *
         * //for (int i = 0; i < 100; i++)
         * //{
         * //    goList.Add(Instantiate(prefab) as GameObject);
         * //}
         *
         * Debug.Log(string.Format(" {0} Instantiate Time : {1} ", "binary_SkeletonGraphic",
         *  Time.realtimeSinceStartup - preTime));
         *
         *
         * go.transform.SetParent(canvas.transform, false);
         *
         * //for (int i = 0; i < 100; i++)
         * //{
         * //    goList[i].transform.SetParent(canvas.transform, false);
         * //}
         *
         *
         *
         *
         * preTime = Time.realtimeSinceStartup;
         * ab = loadSceneMgr.LoadBundle("json_SkeletonGraphic");
         * prefabAssetPath = "Assets/res/Prefabs/json_SkeletonGraphic.prefab";
         * prefab = ab.LoadAsset<Object>(prefabAssetPath);
         * Debug.Log(string.Format(" {0} Load Bundle Time : {1} ", "json_SkeletonGraphic",
         *  Time.realtimeSinceStartup - preTime));
         *
         *
         * preTime = Time.realtimeSinceStartup;
         * go = Instantiate(prefab) as GameObject;
         * //goList = new List<GameObject>();
         * //for (int i = 0; i < 100; i++)
         * //{
         * //    goList.Add(Instantiate(prefab) as GameObject);
         * //}
         * Debug.Log(string.Format(" {0} Instantiate Time : {1} ", "json_SkeletonGraphic",
         *  Time.realtimeSinceStartup - preTime));
         *
         * go.transform.SetParent(canvas.transform, false);
         * //for (int i = 0; i < 100; i++)
         * //{
         * //    goList[i].transform.SetParent(canvas.transform, false);
         * //}
         *
         */
    }
示例#59
0
        /// <summary>
        /// Step 4:对比本地和服务器配置数据信息
        /// </summary>
        /// <param name="remoteVersionPath"></param>
        private void CompareVersion(string remoteVersionPath)
        {
            mParent.UpdateProgress("比对更新文件中", 0);

            string              remoteABPath = Application.persistentDataPath + "/" + BundleCommon.ResVersion + "/Out/assetbundle";
            AssetBundle         remoteAB     = null;
            AssetBundleManifest remoteABM    = null;

            if (File.Exists(remoteABPath))
            {
                remoteAB = AssetBundle.LoadFromFile(remoteABPath);
            }
            if (null != remoteAB)
            {
                remoteABM = remoteAB.LoadAsset("AssetBundleManifest") as AssetBundleManifest;

                remoteAB.Unload(false);
            }

            remoteConfigs = XMLTool.LoadAllABConfig(remoteVersionPath);
            localConfigs  = XMLTool.LoadAllABConfig(BundleCommon.UserVersionPath);
            streamConfigs = XMLTool.LoadAllABConfig(BundleCommon.StreamUserVersionPath, true);

            updateABConfigs = new List <AssetBundleConfig>();

            if (null != remoteConfigs)
            {
                Dictionary <string, AssetBundleConfig> localConfigDict  = new Dictionary <string, AssetBundleConfig>();
                Dictionary <string, AssetBundleConfig> remoteConfigDict = new Dictionary <string, AssetBundleConfig>();
                Dictionary <string, AssetBundleConfig> streamConfigDict = new Dictionary <string, AssetBundleConfig>();
                Dictionary <string, string[]>          dps = new Dictionary <string, string[]>();

                for (int i = 0; i < remoteConfigs.Count; i++)
                {
                    remoteConfigDict[remoteConfigs[i].RelativePath] = remoteConfigs[i];

                    mABFileMgr.AddABFile(remoteConfigs[i]);
                }
                for (int i = 0; i < localConfigs.Count; i++)
                {
                    localConfigDict[localConfigs[i].ABName] = localConfigs[i];
                }

                if (null != streamConfigs)
                {
                    for (int i = 0; i < streamConfigs.Count; i++)
                    {
                        streamConfigDict[streamConfigs[i].ABName] = streamConfigs[i];
                    }
                }

                int totalSize = remoteConfigs.Count;
                for (int i = 0; i < totalSize; i++)
                {
                    AssetBundleConfig localCfg  = null;
                    AssetBundleConfig streamCfg = null;
                    bool isNew = false;
                    if (localConfigDict.TryGetValue(remoteConfigs[i].ABName, out localCfg))
                    {
                        if (localCfg.MD5Value.Equals(remoteConfigs[i].MD5Value))
                        {
                            isNew = false;

                            mABFileMgr.SetABFileState(remoteConfigs[i].RelativePath, ABFileState.DOWNLOADED);
                        }
                        else
                        {
                            isNew = true;
                        }
                    }
                    else
                    {
                        if (streamConfigDict.TryGetValue(remoteConfigs[i].ABName, out streamCfg))
                        {
                            if (streamCfg.MD5Value.Equals(remoteConfigs[i].MD5Value))
                            {
                                isNew = false;

                                mABFileMgr.SetABFileState(remoteConfigs[i].RelativePath, ABFileState.STREAMEXIT);
                            }
                            else
                            {
                                isNew = true;
                            }
                        }
                        else
                        {
                            isNew = true;
                        }
                    }

                    if (isNew)
                    {
                        string   relativePath = remoteConfigs[i].RelativePath;
                        string[] dp           = remoteABM.GetAllDependencies(relativePath.Substring(1, relativePath.Length - 1));
                        dps[relativePath] = dp;
                    }
                }

                if (dps.Count > 0)
                {
                    CompareThread.StartCompare(remoteConfigs, remoteConfigDict, localConfigDict, streamConfigDict, dps, updateABConfigs, CompareProgress, CompareFinish);
                }
                else
                {
                    CompareFinish();
                }
            }
            else
            {
                CompareFinish();
            }
        }
示例#60
0
 private void Unload()
 {
     m_CatalogAssetBundle?.Unload(true);
     m_CatalogAssetBundle = null;
 }