using System.Collections;
using System.IO;
using UnityEngine;
public class ResourceMgr
{
#region Instance
private static ResourceMgr _inst;
public static ResourceMgr Inst
{
get { return _inst = _inst ?? new ResourceMgr(); }
}
#endregion
private ResourceMgr()
{
Init();
}
private string _streamPath;
private Hashtable _resourceTable; //缓存从Resource中加载的资源
private void Init()
{
_resourceTable = new Hashtable();
_streamPath = Application.streamingAssetsPath;
}
public T LoadAsset<T>(string path, bool isCache = true) where T : Object
{
if (_resourceTable.Contains(path))
return _resourceTable[path] as T;
var assets = Resources.Load<T>(path);
if (assets == null)
{
Debug.LogFormat(" assets is not found at Path:{0}", path);
return null;
}
if (isCache)
_resourceTable.Add(path, assets);
return assets;
}
public WWW LoadAssetAsStream(string name, bool isCache = true)
{
if (_resourceTable.Contains(name))
return _resourceTable[name] as WWW;
var www = new WWW("file:///" + Path.Combine(_streamPath, name));
Debug.Log(Path.Combine(_streamPath, name));
while (!www.isDone) {}
return www;
}
public T InstantiateAsset<T>(string path) where T:Object
{
var obj = LoadAsset<T>(path);
var go = GameObject.Instantiate<T>(obj);
if (go == null)
Debug.LogError("Instantiate {0} failed!", obj);
return go;
}
public void ClearAssetsCache()
{
foreach (Object asset in _resourceTable)
{
#if UNITY_EDITOR
GameObject.DestroyImmediate(asset, true);
#else
GameObject.DestroyObject(asset);
#endif
}
_resourceTable.Clear();
}
}
用法:
_mieHuoClip = ResourceMgr.Inst.LoadAsset<AudioClip>("miehuoqi");
ResourceMgr.Inst.LoadAssetAsStream(AppDefine.Bundle_Root_Audio + pointValue + ".ogg");
ResourceMgr.Inst.InstantiateAsset<GameObject>("Network/RoleItem");