Cache

From Unify Community Wiki
Jump to: navigation, search

The problem is when use WWW,if cached AssetBundle is exist, and you want load twice,unity will throw error. then can use this solution, if you like.

AssetBundleDictionary manage the cache resource.

#pragma strict
import System.Collections.Generic;
//////////////////////////////////////////////////////
///工程,下载的资源管理
///AssetBundle字典. 
///url为key,value:AssetBundle
//////////////////////////////////////////////////////

class AssetBundleDictionary{
	/**资源字典.*/
	private static var dict:Dictionary.<String,AssetBundle> = new Dictionary.<String,AssetBundle>();
	
	static function Add(url:String,go:AssetBundle){
		Remove(url);
		dict.Add(url,go);
	}
	
	static function Remove(url:String){
		if(Contains(url)){
			dict[url].Unload(true);
			dict.Remove(url);
		}
	}
	
	static function Clear(){
		dict.Clear();
	}
	/**
		根据key获取一个AssetBundle
	*/
	static function Get(url:String):AssetBundle{
		return dict[url];
	}
	/**
		从 字典中获取 mainAsset
	*/
	static function GetMainAsset(url:String):Object{
		if(Contains(url)){
			return dict[url].mainAsset;
		}
		return null;
	}
	/**
		字典中是否包含key
	*/
	static function Contains(url:String):boolean{
		return dict.ContainsKey(url);
	}
}

2 LoadComponent , manage loading.

#pragma strict
//////////////////////////////////////////////////////
///一个下载组件,下载时附加到GameObject
//////////////////////////////////////////////////////
/** www */
var www:WWW;
/** loading function */
var progressFun:Function;

/**
	载入素材
	@param url
	@param version,为-1时,不从缓存载入.
	@param onOk : function(prefab:Game):void
*/
function Load(url:String,version:int,onOk:Function){
	if(version == -1){
		www = WWW(url);
	}else{
		AssetBundleDictionary.Remove(url);
		www = WWW.LoadFromCacheOrDownload(url,version);
	}
	yield WaitForLoading();
	AssetBundleDictionary.Add(url, www.assetBundle);
	onOk(AssetBundleDictionary.GetMainAsset(url));
}
/**载入文本.*/
function LoadText(url:String,onOk:Function){
	www = WWW(url);
	yield WaitForLoading();
	onOk(www.text);
}

/**等待完成.*/
private function WaitForLoading(){
	while(! www.isDone){
		if(www.error){
			Debug.Log(www.error);
			break;
		}
		if(progressFun)
			progressFun(www.progress);
		yield;
	}
}
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox