Inheritance: MonoBehaviour
    public static AssetBundleLoader GetInstance()
    {
		if (instance == null){
			instance = FindObjectOfType(typeof(AssetBundleLoader)) as AssetBundleLoader;
			if (instance == null){ // no AssetBundleLoader in the level, add one
				GameObject dgo = new GameObject("AssetBundleLoader");
				instance = dgo.AddComponent<AssetBundleLoader>();
			}
		}
  	    return instance;
    }	
	// Use this for initialization
	void Start ()
	{
		AssetBundle ab = null;

		string path = ""+Application.dataPath + "/example/bundle/item.unity3d";
		if(FileLoader.IsExist(path))
		{
			byte[] data = FileLoader.ReadAllBytes(path);
			this.loader = AssetBundleLoader.LoadBinary(data,finish_callback,error_callback);
		}
	}
示例#3
0
    public override bool Load(Priority priority, out bool process)
    {
        process = this.process;
        if (loadStatus == LoadStatus.UNLOAD)
        {
            process = this.process;

            Action <UnityEngine.Object> onLoadCallBack = (abObject) =>
            {
                this.loadStatus = LoadStatus.LOADEND;
                this.process    = true;
                onLoadFinishCallBack.Invoke(abObject);
            };

            switch (GameSetting.Instance.runType)
            {
            case RunType.PATCHER_SA_PS:
                AssetBundleLoader.LoadAsset(name, assetType, onLoadCallBack);
                break;

            case RunType.NOPATCHER_SA:
                AssetBundleLoader.LoadAsset(name, assetType, onLoadCallBack);
                break;

            case RunType.NOPATCHER_RES:
                ResourcesLoader.LoadAsset(name, assetType, onLoadCallBack);
                break;
            }

            loadStatus = LoadStatus.LOADING;
        }
        else if (loadStatus == LoadStatus.LOADING)
        {
            process = this.process;
        }
        else if (loadStatus == LoadStatus.LOADEND)
        {
            process = this.process;
        }

        return(true);
    }
示例#4
0
    public override void AddLoader(BaseLoader loader)
    {
        var assetBundleLoader = (AssetBundleLoader)loader;

        //从缓存池中找到是否有相同 path 如果有则附加 finishCallback
        //没有的话加入到缓存池中
        AssetBundleLoader abLoader = null;
        if (!abLoaderDic.TryGetValue(assetBundleLoader.path, out abLoader))
        {
            abLoaderDic.Add(assetBundleLoader.path, assetBundleLoader);
            ////Logx.Logz("AssetBundleLoadProcess AddLoader : no loader cache and start a new loader : " + assetBundleLoader.path);
            base.AddLoader(loader);
        }
        else
        {
            ////Logx.Logz("AssetBundleLoadProcess AddLoader : have loader cache " + assetBundleLoader.path);
            abLoader.finishLoadCallback += assetBundleLoader.finishLoadCallback;
            abLoader.refCount += 1;
        }
    }
示例#5
0
    public void Update()
    {
        mLoadedAssetBundleListKeys.Clear();
        mLoadedAssetBundleListValues.Clear();
        AssetBundleLoader assetBundleLoader = FrameBase.mResourceManager.getAssetBundleLoader();
        var bundleList = assetBundleLoader.getAssetBundleInfoList();

        foreach (var item in bundleList)
        {
            if (item.Value.getAssetBundle() != null)
            {
                mLoadedAssetBundleListKeys.Add(item.Key);
                AssetBundleDebug bundleDebug = new AssetBundleDebug(item.Value.getBundleName());
                bundleDebug.mAssetList.AddRange(item.Value.getAssetList().Values);
                bundleDebug.mParentBundles.AddRange(item.Value.getParents().Keys);
                bundleDebug.mChildBundles.AddRange(item.Value.getChildren().Keys);
                mLoadedAssetBundleListValues.Add(bundleDebug);
            }
        }
    }
示例#6
0
    public void OnLoginAckPlayerLoginResult(byte[] pBuf)
    {
        GameProto.LoginAckPlayerLoginResult oRet = GameProto.LoginAckPlayerLoginResult.Parser.ParseFrom(pBuf);
        if (oRet == null)
        {
            SampleDebuger.Log("OnTest error parse");
            return;
        }

        SampleDebuger.Log("login ret : " + oRet.DwResult.ToString());

        AssetBundleLoader.Instance().LoadLevelAsset(GameConstant.g_szLobbyScene, delegate()
        {
            if (!string.IsNullOrEmpty(PlayerData.Instance().proGameIp))
            {
                H5Manager.Instance().ConnectGame(PlayerData.Instance().proGameIp, PlayerData.Instance().proGamePort);
            }
        }
                                                    );
    }
示例#7
0
    // Use this for initialization
    void BeginExample()
    {
        DontDestroyOnLoad(gameObject);

        // Set active variants.
        AssetBundleLoader.activeVariants = activeVariants;

        if (async)
        {
            AssetBundleLoader.LoadManifestAsync(() =>
            {
                AssetBundleLoader.LoadSceneAsync(variantSceneBundle, variantSceneName, addictive, null, null);
            });
        }
        else
        {
            AssetBundleLoader.LoadManifest();
            AssetBundleLoader.LoadScene(variantSceneBundle, variantSceneName, addictive);
        }
    }
示例#8
0
    Dictionary <GameObject, UnityEngine.Object> loadedGameObject; // GameObject -> asset(Prefab)

    //资源管理器激活
    private void Awake()
    {
        instance = this;//实例为自己.单例模式
        //Applicaiton.dataPath在安卓上的路径是/data/app/package name-1/base.apk
        //ios是:/var/containers/Bundle/Application/app sandbox/xxx.app/Data

        if (Application.platform == RuntimePlatform.Android)//如果是安卓平台,则资源包根路径是Application.dataPath + "!assets"合并上"res"
        {
            assetBundleRoot = Path.Combine(Application.dataPath + "!assets", "res");
        }
        else
        {
            //streamingAssetsPath在android是:jar:file:///data/app/package name-1/base.apk!/assets
            //ios:/var/containers/Bundle/Application/app sandbox/test.app/Data/Raw
            assetBundleRoot = Path.Combine(Application.streamingAssetsPath, "res");
        }
        //补丁路径
        //Application.persistentDataPath:
        //安卓:/storage/emulated/0/Android/data/package name/files
        //ios:/var/mobile/Containers/Data/Application/app sandbox/Documents
        string patchRoot = Path.Combine(Application.persistentDataPath, "res");

        //创建一个资源包加载器,参数是资源包根路径和补丁根路径, 以及manifest的相对路径这里是res
        abLoader = new AssetBundleLoader(assetBundleRoot, patchRoot, "res");

        //创建异步加载请求列表.刚开始是空的.
        asyncRequests = new Dictionary <string, List <LoadAssetRequest> >();
        //创建已经加载的资源字典,刚开始是空的.
        loadedAsset = new Dictionary <UnityEngine.Object, string>();
        //已经加载的游戏对象字典.刚开始是空的.
        loadedGameObject = new Dictionary <GameObject, UnityEngine.Object>();
        //创建对象以及其引用数量的关系列表.刚开始是空的.
        refCount = new Dictionary <UnityEngine.Object, int>();

        //切换场景的时候这个对象是不允许被销毁.
        DontDestroyOnLoad(this);
#if UNITY_EDITOR
        //如果是编辑器还要创建一个编辑器加载资源请求列表,刚开始是空的.
        editorLoadAssetRequests = new List <LoadAssetRequest>();
#endif
    }
示例#9
0
    /// <summary>
    /// After Init Modules, coroutine
    /// </summary>
    /// <returns></returns>
    public override IEnumerator OnGameStart()
    {
        Log.Info(I18N.Get("btn_billboard"));
        // Print AppConfigs
        // Log.Info("======================================= Read Settings from C# =================================");
        foreach (BillboardSetting setting in BillboardSettings.GetAll())
        {
            Debug.Log(string.Format("C# Read Setting, Key: {0}, Value: {1}", setting.Id, setting.Title));
        }
        AssetBundleLoader.Load($"uiatlas/{UIModule.Instance.CommonAtlases[0]}", (isOk, ab) =>
        {
            if (isOk && ab)
            {
                var atlas = ab.LoadAsset <SpriteAtlas>("atlas_common");
                ABManager.SpriteAtlases["atlas_common"] = atlas;
            }
        });
        yield return(null);

        UIModule.Instance.OpenWindow("Login", 888);

        // Test Load a scene in asset bundle
        SceneLoader.Load("Scene/Scene1001/Scene1001");

        //预加载公告界面
        // UIModule.Instance.PreLoadUIWindow("Billboard");
        //UIModule.Instance.OpenWindow("Billboard");
        // 测试Collect函数,立即回收所有资源
        var path        = "ui/UIRoleInfo";
        var assetLoader = AssetBundleLoader.Load(path);

        while (!assetLoader.IsCompleted)
        {
            yield return(null);
        }
        yield return(new WaitForSeconds(1));

        assetLoader.Release();

        KResourceModule.Collect();
    }
示例#10
0
    public void GetEbi()
    {
        var buttonImage = GameObject.Find("DetailButton").GetComponent <Image>();

        buttonImage.color = Color.gray;

        detailButton.transform.SetParent(canvas.transform, true);
        var resourceName        = "Assets/BundledResources/Resources/OnDemandOnShop/ebi.png";
        var containedBundleData = AssetBundleLoader.onMemoryBundleList.bundles
                                  .Where(bundle => bundle.resources.Contains(resourceName))
                                  .FirstOrDefault();

        StartCoroutine(AssetBundleLoader.DownloadBundleThenLoadAsset(
                           resourceName,
                           containedBundleData,
                           (Sprite s) => {
            buttonImage.color  = Color.white;
            buttonImage.sprite = s;
        }
                           ));
    }
示例#11
0
    public void OnServerInfo(string szData)
    {
        SampleDebuger.Log(szData);
        ServerListInfo oServerList = JsonUtility.FromJson <ServerListInfo>(szData);

        if (oServerList.server_infos.Count == 0)
        {
            SampleDebuger.LogError("can't find server list!!!!");
            return;
        }

        AssetBundleLoader.Instance().LoadAsset(
            GameObjectConstant.GetABUIPath(GameObjectConstant.g_szLoginServerList),
            GameObjectConstant.GetABName(GameObjectConstant.g_szLoginServerList),
            delegate(UnityEngine.Object ob)
        {
            LoginServerList pList = LoginServerList.CreateInstance(ob, MainCanvas.Instance().transform);
            pList.SetServerListInfo(oServerList);
        }
            );
    }
    private void finish_callback(object obj)
    {
        Debug.Log("Zip Finished");

        AssetBundle ab = null;

        string path = "" + Application.dataPath + "/example/ab_zip/item_uncompress.unity3d";

        if (FileLoader.IsExist(path))
        {
            ab = AssetBundleLoader.CreateFromFile(path);
            GameObject.Instantiate(ab.mainAsset);
        }

        path = "" + Application.dataPath + "/example/ab_zip/Terrain_uncompress.unity3d";
        if (FileLoader.IsExist(path))
        {
            ab = AssetBundleLoader.CreateFromFile(path);
            GameObject.Instantiate(ab.mainAsset);
        }
    }
示例#13
0
    /// <summary>
    /// 初始化资源包
    /// </summary>
    /// <param name="lst"></param>
    public void InitAssetBundle(List <DownloadDataEntity> lst)
    {
        if (lst == null)
        {
            return;
        }
        for (int i = 0; i < lst.Count; ++i)
        {
            if (lst[i].FullName.IndexOf("scene/scene_", StringComparison.CurrentCultureIgnoreCase) > -1)
            {
                continue;
            }

            string dpsPath = LocalFileManager.Instance.LocalFilePath + lst[i].FullName;
            if (!m_DpsAssetBundleLoaderDic.ContainsKey(dpsPath))
            {
                AssetBundleLoader loader = new AssetBundleLoader(lst[i].FullName);
                m_DpsAssetBundleLoaderDic[dpsPath] = loader;
            }
        }
    }
示例#14
0
    protected IEnumerator InstantiateGameObjectAsync(string assetBundleName, string assetName)
    {
        if (!initialized)
        {
            yield return(StartCoroutine(Initialize()));

            initialized = true;
            Debug.Log("Initialized");
        }

        Debug.Log(">>>" + assetBundleName + "  " + assetName);
        // This is simply to get the elapsed time for this phase of AssetLoading.
        float startTime = Time.realtimeSinceStartup;

        // Load asset from assetBundle.
        AssetBundleLoadAssetOperation request = AssetBundleLoader.LoadAssetAsync(assetBundleName, assetName, typeof(GameObject));

        if (request == null)
        {
            yield break;
        }
        yield return(StartCoroutine(request));

        // Get the asset.
        GameObject prefab = request.GetAsset <GameObject>();

        if (prefab != null)
        {
            Vector3    infront      = new Vector3(0.5f, -0.5f, 2.0f);
            Vector3    position     = Camera.main.ViewportToWorldPoint(infront);
            GameObject furnitureFab = GameObject.Instantiate(prefab, position, Quaternion.identity);
            furnitureFab.SetActive(true);
            furnitures.Add(furnitureFab);
        }

        // Calculate and display the elapsed time.
        float elapsedTime = Time.realtimeSinceStartup - startTime;

        Debug.Log(assetName + (prefab == null ? " was not" : " was") + " loaded successfully in " + elapsedTime + " seconds");
    }
示例#15
0
    /// <summary>
    /// 开始加载文件
    /// </summary>
    /// <param name="url"></param>
    /// <param name="type"></param>
    /// <param name="prority"></param>
    /// <param name="Complete"></param>
    public void Load(string url, EnResourceType type, EnLoadPrority prority, CreateGameObjectDelegate Complete)
    {
        string            abPath = PathUtil.GetAbUrl(url, type);
        AssetBundleLoader loader = GetLoader(abPath);

        //已经在加载
        if (loader != null && loader.isInit)
        {
            //加载完毕
            if (loader.isLoadComplete)
            {
                //是否需要创建
                if (loader.isCreateComplete)
                {
                    CreateAsset(loader);
                }
                else
                {
                    LoadAsset(loader);
                }
            }
        }
        //没有加载过
        else
        {
            if (!assetBundleDataMaps.ContainsKey(abPath))
            {
                Loger.Error(abPath);
                return;
            }
            loader = CreateLoader(assetBundleDataMaps[abPath], prority);
        }
        loader.AddCreateComplete(Complete);
        loader.AddLoadComplete(LoadAsset);
        loader.prority = prority;
        if (!loader.isLoadComplete)
        {
            isSortWaitLoadFile = true;
        }
    }
    internal void LoadComplete(AssetBundleLoader loader)
    {
        _requestRemain++;
        _currentLoadQueue.Remove(loader);
        _progress.loader   = loader;
        _progress.complete = _progress.total - _currentLoadQueue.Count;
        if (onProgress != null)
        {
            onProgress(_progress);
        }

        //all complete
        if (_currentLoadQueue.Count == 0 && _nonCompleteLoaderSet.Count == 0)
        {
            //Action<bool> allLoadFinishedEventHandler = this.m_allLoadFinishedEventHandler;
            //this.m_allLoadFinishedEventHandler = null;
            //try
            //{
            //    allLoadFinishedEventHandler(!this.m_bLoadError);
            //}
            //catch (Exception exception)
            //{
            //    Debug.LogException(exception);
            //}
            //Debug.Log("AllFinish");
            _isCurrentLoading = false;

            var e = _thisTimeLoaderSet.GetEnumerator();
            while (e.MoveNext())
            {
                AssetBundleLoader cur = e.Current;
                if (cur.bundleInfo != null)
                {
                    cur.bundleInfo.ResetLifeTime();
                }
            }
            _thisTimeLoaderSet.Clear();
        }
    }
示例#17
0
        public IEnumerator LoadUIAsset(UILoadState loadState, UILoadRequest request)
        {
            float  beginTime = Time.realtimeSinceStartup;
            string path      = string.Format("ui/{0}.prefab", loadState.TemplateName);
            var    loader    = AssetBundleLoader.Load(path);

            while (!loader.IsCompleted)
            {
                yield return(null);
            }
            if (AppConfig.IsLogAbLoadCost)
            {
                Log.Info("{0} Load AB, cost:{1:0.000}s", loadState.TemplateName, Time.realtimeSinceStartup - beginTime);
            }
            if (AppConfig.IsSaveCostToFile)
            {
                LogFileRecorder.WriteUILog(loadState.TemplateName, LogFileRecorder.UIState.LoadAB, Time.realtimeSinceStartup - beginTime);
            }
            if (loader.Bundle == null)
            {
                yield break;
            }

            beginTime = Time.realtimeSinceStartup;
            var req = loader.Bundle.LoadAssetAsync <GameObject>(loadState.TemplateName);

            while (!req.isDone)
            {
                yield return(null);
            }
            request.Asset = GameObject.Instantiate(req.asset);
            loadState.UIResourceLoader = loader;
            if (AppConfig.IsLogAbLoadCost)
            {
                var cost = Time.realtimeSinceStartup - beginTime;
                Log.Info($"Load Asset from {0}, cost:{1:0.###} s", loadState.TemplateName, cost);
                LogFileRecorder.WriteUILog(loadState.TemplateName, LogFileRecorder.UIState.LoadAsset, cost);
            }
        }
示例#18
0
    private void OnLoginAckPlayerLeaveTeam(byte[] pBuf)
    {
        GameProto.LoginAckPlayerLeaveTeam oRet = GameProto.LoginAckPlayerLeaveTeam.Parser.ParseFrom(pBuf);
        if (oRet == null)
        {
            SampleDebuger.Log("OnLoginAckPlayerLeaveTeam error parse");
            return;
        }

        SampleDebuger.Log("OnLoginAckPlayerLeaveTeam result : " + oRet.DwResult.ToString());
        if (oRet.DwResult != 0)
        {
            return;
        }
        if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name != GameConstant.g_szLobbyScene)
        {
            AssetBundleLoader.Instance().LoadLevelAsset(GameConstant.g_szLobbyScene, delegate()
            {
            }
                                                        );
        }
    }
示例#19
0
    /// <summary> 加载依赖文件配置 </summary>
    private void LoadManifestBundle()
    {
        if (m_Manifest != null)
        {
            return;
        }
        string assetName = string.Empty;

#if UNITY_STANDALONE_WIN
        assetName = "Windows";
#elif UNITY_ANDROID
        assetName = "Android";
#elif UNITY_IPHONE
        assetName = "iOS";
#endif
        using (AssetBundleLoader loader = new AssetBundleLoader(assetName))
        {
            //abLoader = loader;
            m_Manifest = loader.LoadAsset <AssetBundleManifest>("AssetBundleManifest");
        }
        Debuger.Log("加载依赖文件配置 完毕");
    }
示例#20
0
        private void CreateInternalEffect(Effect vo)
        {
            try
            {
                curEffectVo  = vo;
                curEffectUrl = vo.URL;

                if (!resDictionary.ContainsKey(curEffectUrl))
                {
                    Log.info(this, "load effect asset " + curEffectUrl);
                    AssetBundleLoader loader = AssetManager.Instance.LoadAsset <GameObject>(curEffectUrl, EffectLoaded);
                }
                else
                {
                    EffectLoaded(resDictionary[curEffectUrl]);
                }
            }
            catch (Exception e)
            {
                Log.error(this, "CreateEffect error, exception is: " + e.Message);
            }
        }
示例#21
0
    public IEnumerator Setup()
    {
        assetBundlePreloader = new AssetBundlePreloader();

        var loaderTestObj = new AssetBundleLoaderTests();
        var listCor       = loaderTestObj.LoadListFromWeb(abListPath);

        yield return(listCor);

        var assetBundleList = listCor.Current as AssetBundleList;

        loader = new AssetBundleLoader(identity => abDlPath + assetBundleList.version + "/");
        loader.UpdateAssetBundleList(assetBundleList);


        var cleaned = loader.CleanCachedAssetBundles();

        if (!cleaned)
        {
            Fail("clean cache failed 1.");
        }
    }
示例#22
0
    private void OnGUI()
    {
        if (GUILayout.Button("加载Prefab", GUILayout.MinWidth(100), GUILayout.MinHeight(60)))
        {
            StartCoroutine(TestLoadUI());
        }

        if (GUILayout.Button("卸载Prefab", GUILayout.MinWidth(100), GUILayout.MinHeight(60)))
        {
            UnLoadAB();
        }

        if (GUILayout.Button($"执行{执行次数}次 加载->卸载", GUILayout.MinWidth(100), GUILayout.MinHeight(60)))
        {
            StartCoroutine(LoopTest());
        }

        if (GUILayout.Button("加载不存在的资源", GUILayout.MinWidth(100), GUILayout.MinHeight(60)))
        {
            AssetBundleLoader.Load("aa/bb.ab");
        }
    }
示例#23
0
        private async Task LoadAllMetaDataForLoader(AssetBundleLoader loader, bool createIfNotExisting = false)
        {
            var sw = DebugTimer.StartNew("Loading Metadata");

            foreach (var assetMetaPath in loader.CollectFiles(_pluginDirs))
            {
                if (_metaData.TryGetValue(assetMetaPath.RelativePath + ".meta", out _))
                {
                    continue;
                }

                if (!assetMetaPath.HasMetaData)
                {
                    if (createIfNotExisting)
                    {
                        var comp = await this[PathTools.ToRelativePath(assetMetaPath.Path)];

                        if (comp == null)
                        {
                            continue;
                        }

                        var metaData = new PreloadMetaData(assetMetaPath, comp, comp.AssetTypeDefinition);
                        metaData.SaveToFile();
                        _metaData.Add(assetMetaPath.RelativePath + ".meta", metaData);
                    }
                }
                else
                {
                    var metaData = new PreloadMetaData(assetMetaPath);
                    metaData.LoadFromFile();
                    metaData.IsFavorite = _config.IsFavorite(PathTools.ToRelativePath(assetMetaPath.Path));
                    _metaData.Add(assetMetaPath.RelativePath + ".meta", metaData);
                }
            }

            sw.Print(_logger);
        }
示例#24
0
    /// <summary>
    /// After Init Modules, coroutine
    /// </summary>
    /// <returns></returns>
    public override IEnumerator OnGameStart()
    {
        WaitForSeconds wait = new WaitForSeconds(1);

        while (DownloadManager.Instance.DownloadFinish == false)
        {
            yield return(wait);
        }
        Log.Info(I18N.Get("btn_billboard"));
        // Print AppConfigs
        // Log.Info("======================================= Read Settings from C# =================================");
        foreach (BillboardSetting setting in BillboardSettings.GetAll())
        {
            Debug.Log(string.Format("C# Read Setting, Key: {0}, Value: {1}", setting.Id, setting.Title));
        }

        UIModule.Instance.OpenWindow("UILogin", 888);

        // Test Load a scene in asset bundle
        SceneLoader.Load("Scene/Scene1001/Scene1001");

        //预加载公告界面
        // UIModule.Instance.PreLoadUIWindow("Billboard");
        //UIModule.Instance.OpenWindow("Billboard");
        // 测试Collect函数,立即回收所有资源
        var path        = "ui/UIRoleInfo";
        var assetLoader = AssetBundleLoader.Load(path);

        while (!assetLoader.IsCompleted)
        {
            yield return(null);
        }
        yield return(new WaitForSeconds(1));

        assetLoader.Release();

        KResourceModule.Collect();
    }
    internal AssetBundleLoader CreateLoader(string abFileName, string oriName = null)
    {
        AssetBundleLoader loader = null;

        if (_loaderCache.ContainsKey(abFileName))
        {
            loader = _loaderCache[abFileName];
        }
        else
        {
#if _AB_MODE_
            AssetBundleData data = _depInfoReader.GetAssetBundleInfo(abFileName);
            if (data == null && oriName != null)
            {
                data = _depInfoReader.GetAssetBundleInfoByShortName(oriName.ToLower());
            }
            if (data == null)
            {
                Debug.Log("MIssLoad:" + oriName);
                MissAssetBundleLoader missLoader = new MissAssetBundleLoader();
                missLoader.bundleManager = this;
                return(missLoader);
            }

            loader = this.CreateLoader();
            loader.bundleManager = this;
            loader.bundleData    = data;
            loader.bundleName    = data.fullName;
#else
            loader = this.CreateLoader();
            loader.bundleManager = this;
            loader.bundleName    = abFileName;
#endif
            _loaderCache[abFileName] = loader;
        }

        return(loader);
    }
示例#26
0
    static protected void LoadAssetBundleInternal(string assetBundleName, bool isLoadingAssetBundleManifest = true)
    {
        LoadedAssetBundle bundle = null;
        m_LoadedAssetBundles.TryGetValue(assetBundleName, out bundle);
        if (bundle != null)
        {
            bundle.m_ReferencedCount++;
            return;
        }

        if (m_LoadingRequest.ContainsKey(assetBundleName))
        {
            return;
        }
        string url = AssetBundleLoader.Instance().GetBundleUrl(assetBundleName);
		SampleDebuger.Log("ab url: " + url);
#if UNITY_WEBGL
		WWW request = new WWW(url);
#else
		AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(url);
#endif
		m_LoadingRequest.Add(assetBundleName, request);
    }
示例#27
0
 protected LOAD_SOURCE mLoadSource;                                                                          // 0为从Resources加载,1为从AssetBundle加载
 public ResourceManager()
 {
     mCreateObject      = true;
     mAssetBundleLoader = new AssetBundleLoader();
     mResourceLoader    = new ResourceLoader();
     mTypeSuffixList    = new Dictionary <Type, List <string> >();
     registeSuffix(Typeof <Texture>(), ".png");
     registeSuffix(Typeof <Texture2D>(), ".png");
     registeSuffix(Typeof <GameObject>(), ".prefab");
     registeSuffix(Typeof <GameObject>(), ".fbx");
     registeSuffix(Typeof <Material>(), ".mat");
     registeSuffix(Typeof <Shader>(), ".shader");
     registeSuffix(Typeof <AudioClip>(), ".wav");
     registeSuffix(Typeof <AudioClip>(), ".ogg");
     registeSuffix(Typeof <AudioClip>(), ".mp3");
     registeSuffix(Typeof <TextAsset>(), ".txt");
     registeSuffix(Typeof <TextAsset>(), ".bytes");
     registeSuffix(Typeof <RuntimeAnimatorController>(), ".controller");
     registeSuffix(Typeof <RuntimeAnimatorController>(), ".overrideController");
     registeSuffix(Typeof <SpriteAtlas>(), ".spriteatlas");
     registeSuffix(Typeof <Sprite>(), ".png");
     registeSuffix(Typeof <UnityEngine.Object>(), ".asset");
 }
示例#28
0
 protected static Dictionary <Type, List <string> > mTypeSuffixList;            // 资源类型对应的后缀名
 public ResourceManager(string name)
     : base(name)
 {
     mCreateObject      = true;
     mAssetBundleLoader = new AssetBundleLoader();
     mResourceLoader    = new ResourceLoader();
     mTypeSuffixList    = new Dictionary <Type, List <string> >();
     registeSuffix(typeof(Texture), ".png");
     registeSuffix(typeof(Texture2D), ".png");
     registeSuffix(typeof(GameObject), ".prefab");
     registeSuffix(typeof(GameObject), ".fbx");
     registeSuffix(typeof(Material), ".mat");
     registeSuffix(typeof(Shader), ".shader");
     registeSuffix(typeof(AudioClip), ".wav");
     registeSuffix(typeof(AudioClip), ".ogg");
     registeSuffix(typeof(AudioClip), ".mp3");
     registeSuffix(typeof(TextAsset), ".txt");
     registeSuffix(typeof(RuntimeAnimatorController), ".controller");
     registeSuffix(typeof(RuntimeAnimatorController), ".overrideController");
     registeSuffix(typeof(SpriteAtlas), ".spriteatlas");
     registeSuffix(typeof(Sprite), ".png");
     registeSuffix(typeof(UnityEngine.Object), ".asset");
 }
示例#29
0
        public void LoadAssetBundle(string path, int tag, bool cacheLoadedAsset, Action <AssetBundleReference> completeHandle = null)
        {
            if (m_Context != null && m_Context.enable)
            {
#if ASSETMANAGER_LOG_ON
                Debug.LogFormat("[AssetManage]ContextAssetLoader Start load asset bundle {0}.", path);
#endif
                //这里暂时使用匿名函数。
                AssetBundleLoader loader = AssetManager.Instance.LoadAssetBundle(path, tag, cacheLoadedAsset, completeHandle);
                if (loader != null)
                {
                    loader.onBeforeComplete += OnAssetBundleBeforeComplete;
                    m_AssetBundleLoaders.Add(loader);
                    m_AssetBundleCompleteHandles[loader] = completeHandle;
                }
            }
            else
            {
#if ASSETMANAGER_LOG_ON
                Debug.LogFormat("[ContextAssetLoader] Can't load asset bundle {0}.The context is disable", path);
#endif
            }
        }
示例#30
0
    // 从StreamingAsset读取version.jz
    // 从StreamingAsset读取缓存的最新的version.jz
    public static VersionConfig ReadConfig(string versionPath)
    {
        AssetBundle ab = AssetBundleLoader.Load(versionPath);

        if (ab != null)
        {
            TextAsset text = ab.LoadAsset("version") as TextAsset;
            if (text == null)
            {
                return(null);
            }
            string        content = text.text;
            VersionConfig vc      = ReadVersionConfig(content);
            ab.Unload(true);
            // 读取成功
            return(vc);
        }
        else
        {
            // 读取失败
            return(null);
        }
    }
示例#31
0
    /// <summary>
    /// 加载场景
    /// </summary>
    /// <param name="sceneName"></param>
    /// <param name="single"></param>
    /// <param name="async"></param>
    /// <param name="useAssetBundle"></param>
    /// <returns></returns>
    public AssetLoader LoadScene(string sceneName, bool single, bool async, bool useAssetBundle)
    {
        AssetLoader assetLoader = null;

        if (useAssetBundle)
        {
            assetLoader = new AssetBundleLoader(sceneName, async);
        }
        else
        {
            assetLoader = new ResourcesLoader(sceneName, async);
        }
        assetLoader.isSingle = single;
        if (async)
        {
            _waitLoadAssetLoaders.Add(assetLoader);
        }
        else
        {
            assetLoader.Start();
        }
        return(assetLoader);
    }
示例#32
0
    void Awake()
    {
        AssetBundleLoader loader = AssetBundleManager.GetInstance().GetLoader(PathUtil.GetAbUrl("Shader", EnResourceType.Shader));

        for (int i = 0; i < gameList.Length; i++)
        {
            Shader shader     = gameList[i];
            Shader findShader = Shader.Find(shader.name);
            if (findShader != null)
            {
                shader = findShader;
            }
            else
            {
                findShader = loader.LoadAsset <Shader>(shader.name);
                if (findShader != null)
                {
                    shader = findShader;
                }
            }
            sMaps[shader.name] = shader;
        }
    }
示例#33
0
 void LoadBundle(AssetBundleLoader loader)
 {
     if (!loader.isComplete)
     {
         loader.LoadBundle();
         _requestRemain--;
     }
 }
示例#34
0
        internal AssetBundleInfo CreateBundleInfo(AssetBundleLoader loader, AssetBundleInfo abi = null, AssetBundle assetBundle = null)
        {
            if (abi == null)
                abi = new AssetBundleInfo();
            abi.bundleName = loader.bundleName.ToLower();
            abi.bundle = assetBundle;
            abi.data = loader.bundleData;

            _loadedAssetBundle[abi.bundleName] = abi;
            return abi;
        }
示例#35
0
 void Awake()
 {
     assetBundleLoader = GameObject.Find("AssetBundleLoader").GetComponent<AssetBundleLoader>();
     assetBundleFetcher = GameObject.Find("AssetBundleFetcher").GetComponent<AssetBundleFetcher>();
 }
示例#36
0
 void Start()
 {
     loader = new AssetBundleLoader();
 }
示例#37
0
 /// <summary>
 /// 请求加载Bundle,这里统一分配加载时机,防止加载太卡
 /// </summary>
 /// <param name="loader"></param>
 internal void Enqueue(AssetBundleLoader loader)
 {
     if (_requestRemain < 0)
         _requestRemain = 0;
     _requestQueue.Add(loader);
 }
示例#38
0
        internal void LoadComplete(AssetBundleLoader loader)
        {
            _requestRemain++;
            _currentLoadQueue.Remove(loader);

            if (onProgress != null)
            {
                _progress.loader = loader;
                _progress.complete = _progress.total - _currentLoadQueue.Count;
                onProgress(_progress);
            }

            //all complete
            if (_currentLoadQueue.Count == 0 && _nonCompleteLoaderSet.Count == 0)
            {
                _isCurrentLoading = false;

                var e = _thisTimeLoaderSet.GetEnumerator();
                while (e.MoveNext())
                {
                    AssetBundleLoader cur = e.Current;
                    if (cur.bundleInfo != null)
                        cur.bundleInfo.ResetLifeTime();
                }
                _thisTimeLoaderSet.Clear();
            }
        }
示例#39
0
 internal void LoadError(AssetBundleLoader loader)
 {
     Debug.LogWarning("Cant load AB : " + loader.bundleName, this);
     LoadComplete(loader);
 }