【Unity】 Resources.Load资源管理

本文介绍了一个Unity中的资源管理器类ResourceMgr,该类用于管理游戏中的资源加载、实例化及缓存清理等操作。ResourceMgr提供了多种加载资源的方法,如LoadAsset、LoadAssetAsStream和InstantiateAsset,并且支持缓存管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Unity_阿黄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值