Unity3D游戏开发框架-资源管理类ResourceManage

原创 2016年08月29日 12:12:35

原文链接:http://blog.csdn.net/u013108312/article/details/52351850
这里写图片描述
新建文件夹:ResMgr。接着新建三个C#脚本。代码如下:
IResLoadListener.cs
AssetInfo.cs
ResMgr.cs

using UnityEngine;
using System.Collections;

/// <summary>
/// 资源加载回调
/// </summary>
public interface IResLoadListener  
{
    void Finish(object asset);

    void Failure();
}
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// 资源信息
/// </summary>
public class AssetInfo
{
    /// <summary>
    /// 资源
    /// </summary>
    public object asset;

    /// <summary>
    /// 是否常驻内存
    /// </summary>
    public bool isKeepInMemory;

    /// <summary>
    /// 资源堆栈数量
    /// </summary>
    public int stackCount = 0;
}

/// <summary>
/// 资源加载信息
/// </summary>
public class RequestInfo
{
    /// <summary>
    /// 资源反馈信息
    /// </summary>
    public ResourceRequest request;

    /// <summary>
    /// 是否常驻内存
    /// </summary>
    public bool isKeepInMemory;

    /// <summary>
    /// 加载完成之后的回调
    /// </summary>
    public List<IResLoadListener> linsteners;

    public void AddListener(IResLoadListener listener)
    {
        if (linsteners == null)
        {
            linsteners = new List<IResLoadListener>() { listener };
        }
        else
        {
            if (!linsteners.Contains(listener))
            {
                linsteners.Add(listener);
            }
        }
    }

    /// <summary>
    /// 资源名称
    /// </summary>
    public string assetName;

    public string assetFullName
    {
        get
        {
            return ResMgr.Instance.GetFileFullName(assetName);
        }
    }

    /// <summary>
    /// 资源类型
    /// </summary>
    public Type type;

    /// <summary>
    /// 资源是否加载完成
    /// </summary>
    public bool IsDone
    {
        get
        {
            return (request != null && request.isDone);
        }
    }

    /// <summary>
    /// 加载到的资源
    /// </summary>
    public object Asset
    {
        get
        {
            return request != null ? request.asset : null;
        }
    }

    public void LoadAsync()
    {
        request = Resources.LoadAsync(assetFullName, type);
    }
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;

public class ResMgr : EventNode,IEventListener 
{
    private Dictionary<string, string> mAssetPathDic = new Dictionary<string, string>();
    public string GetFileFullName(string assetName)
    {
        if (mAssetPathDic.Count == 0)
        {
            UnityEngine.TextAsset tex = Resources.Load<TextAsset>("res");
            StringReader sr = new StringReader(tex.text);
            string fileName = sr.ReadLine();
            while (fileName != null)
            {
                Debug.Log("fileName =" + fileName);
                string [] ss = fileName.Split('=');
                mAssetPathDic.Add(ss[0], ss[1]);
                fileName = sr.ReadLine();
            }
        }
        return assetName = mAssetPathDic[assetName] + "/" + assetName; 
    }
    /// <summary>
    /// 所有资源字典
    /// </summary>
    private Dictionary<string, AssetInfo> mDicAaaet = new Dictionary<string, AssetInfo>();

    /// <summary>
    /// CPU 个数
    /// </summary>
    private int mProcessorCount = 0;

    private static ResMgr mInstance;
    public static ResMgr Instance
    {
        get
        {
            return mInstance;
        }
    }



    // Awake is called when the script instance is being loaded.
    void Awake()
    {
        mInstance = this;
        DontDestroyOnLoad(this.gameObject);
        AttachEventListener(EventDef.ResLoadFinish, this);
        mProcessorCount = SystemInfo.processorCount > 0 && SystemInfo.processorCount <= 8 ? SystemInfo.processorCount : 1;
    }

    void OnDestroy()
    {
        if (Instance != null)
        {
            Instance.DetachEventListener(EventDef.ResLoadFinish, this);
        }
    }

    /// <summary>
    /// 正在加载的列表
    /// </summary>
    public List<RequestInfo> mInLoads = new List<RequestInfo>();

    /// <summary>
    /// 等待加载的列表
    /// </summary>
    public Queue<RequestInfo> mWaitting = new Queue<RequestInfo>();

    /// <summary>
    /// 资源加载堆栈
    /// </summary>
    public Stack<List<string>> mAssetStack = new Stack<List<string>>();

    #region 加载资源
    public void Load(string assetName, IResLoadListener listener, Type type = null, bool isKeepInMemory = false, bool isAsync = true)
    {
        if (mDicAaaet.ContainsKey(assetName))
        {
            listener.Finish(mDicAaaet[assetName]);
            return;
        }
        if (isAsync)
        {
            LoadAsync(assetName, listener,isKeepInMemory,type);
        }
    }
    #endregion

    #region 异步Res加载
    private void LoadAsync(string assetName, IResLoadListener listener,bool isKeepInMemory,Type type)
    {
        for (int i = 0; i < mInLoads.Count; i++)
        {
            if (mInLoads[i].assetName == assetName)
            {
                mInLoads[i].AddListener(listener);
                return;
            }
        }

        foreach(RequestInfo info in mWaitting)
        {
            if (info.assetName == assetName)
            {
                info.AddListener(listener);
                return;
            }
        }

        RequestInfo requestInfo = new RequestInfo();
        requestInfo.assetName = assetName;
        requestInfo.AddListener(listener);
        requestInfo.isKeepInMemory = isKeepInMemory;
        requestInfo.type = type == null ? typeof(GameObject) : type;
        mWaitting.Enqueue(requestInfo);
    }
 #endregion

    #region 资源处理

        /// <summary>
        /// 从资源字典中取得一个资源
        /// </summary>
        /// <param name="assetName">资源名称</param>
        /// <returns></returns>
        public AssetInfo GetAsset(string assetName)
        {
            AssetInfo info = null;
            mDicAaaet.TryGetValue(assetName,out info);
            return info;
        }

        /// <summary>
        /// 释放一个资源
        /// </summary>
        /// <param name="assetName">资源名称</param>
        public void ReleaseAsset(string assetName)
        {
            AssetInfo info = null;
            mDicAaaet.TryGetValue(assetName, out info);

            if (info != null && !info.isKeepInMemory)
            {
                mDicAaaet.Remove(assetName);
            }
        }

        /// <summary>
        /// 修改资源是否常驻内存
        /// </summary>
        /// <param name="assetName">资源名称</param>
        /// <param name="IsKeepInMemory">是否常驻内存</param>
        public void IsKeepInMemory(string assetName,bool IsKeepInMemory)
        {
            AssetInfo info = null;
            mDicAaaet.TryGetValue(assetName, out info);

            if (info != null)
            {
                info.isKeepInMemory = IsKeepInMemory;
            }
        }
    #endregion

    #region 资源释放以及监听

        /// <summary>
        /// 把资源压入顶层栈内
        /// </summary>
        /// <param name="assetName">资源名称</param>
        public void AddAssetToName(string assetName)
        {
            if (mAssetStack.Count == 0)
            {
                mAssetStack.Push(new List<string>() { assetName });
            }

            List <string> list = mAssetStack.Peek();
            list.Add(assetName);
        }

        /// <summary>
        /// 开始让资源入栈
        /// </summary>
        public void PushAssetStack()
        {
            List<string> list = new List<string>();
            foreach(KeyValuePair<string,AssetInfo> info in mDicAaaet)
            {
                info.Value.stackCount++;
                list.Add(info.Key);
            }

            mAssetStack.Push(list);
        }

        /// <summary>
        /// 释放栈内资源
        /// </summary>
        public void PopAssetStack()
        {
            if (mAssetStack.Count == 0) return;

            List<string> list = mAssetStack.Pop();
            List<string> removeList = new List<string>();
            AssetInfo info = null;
            for (int i = 0; i < list.Count;i++ )
            {
                if (mDicAaaet.TryGetValue(list[i],out info))
                {
                    info.stackCount--;
                    if (info.stackCount < 1 && !info.isKeepInMemory)
                    {
                        removeList.Add(list[i]);
                    }
                }
            }
            for (int i = 0; i < removeList.Count;i++ )
            {
                if (mDicAaaet.ContainsKey(removeList[i]))
                mDicAaaet.Remove(removeList[i]);
            }

            GC();
        }

        /// <summary>
        /// 释放
        /// </summary>
        public void GC()
        {
            Resources.UnloadUnusedAssets();
            System.GC.Collect();
        }


    #endregion

    void Update()
    {
        if (mInLoads.Count > 0)
        {
            for (int i = mInLoads.Count - 1; i >= 0; i--)
            {
                if (mInLoads[i].IsDone)
                {
                    RequestInfo info = mInLoads[i];
                    SendEvent(EventDef.ResLoadFinish, info);
                    mInLoads.RemoveAt(i);
                }
            }
        }

        while (mInLoads.Count < mProcessorCount && mWaitting.Count > 0)
        {
            RequestInfo info = mWaitting.Dequeue();
            mInLoads.Add(info);
            info.LoadAsync();
        }
    }



    public bool HandleEvent(int id, object param1, object param2)
    {
        switch (id)
        {
            case EventDef.ResLoadFinish:
                RequestInfo info = param1 as RequestInfo;
                if (info != null)
                {
                    if (info.Asset != null)
                    {
                        AssetInfo asset = new AssetInfo();
                        asset.isKeepInMemory = info.isKeepInMemory;
                        asset.asset = info.Asset;
                        if (!mDicAaaet.ContainsKey(info.assetName))
                        {
                            mDicAaaet.Add(info.assetName, asset);
                        }

                        for (int i = 0; i < info.linsteners.Count;i++ )
                        {
                            if (info.linsteners[i] != null)
                            {
                                info.linsteners[i].Finish(info.Asset);
                            }
                        }
                        AddAssetToName(info.assetName);
                    }
                }
                else
                {
                    for (int i = 0; i < info.linsteners.Count; i++)
                    {
                        if (info.linsteners[i] != null)
                        {
                            info.linsteners[i].Failure();
                        }
                    }
                }
                return false;
        }
        return false;
    }

    public int EventPriority()
    {
        return 0;
    }
}

原文链接:http://blog.csdn.net/u013108312/article/details/52351850

版权声明:欢迎转载,转载请注明原博客链接:http://blog.csdn.net/u013108312 和本文章的链接。谢谢合作。作者:CircleGood

Unity3d资源管理分析

y 分离资源管理 参考 1.Unity3D占用内存太大的解决方法 - 星尘 讨论AssetBundle-Resources-GameObject 的生命周期...
  • sgnyyy
  • sgnyyy
  • 2014年09月14日 10:40
  • 12545

Unity3D - 资源管理

Unity3D的资源管理总结
  • ynnmnm
  • ynnmnm
  • 2015年04月01日 16:33
  • 5811

Unity3D 游戏项目实例教程之资源加载管理器

资源加载管理器,顾名思义,就是负责加载资源的, Unity 中负责加载资源的是 WWW 类,根据 Flash 的游戏加载风格,我修改成了实用并且简单的类库! 我们先来看下最终结果的示例演示代码: u...

Unity3d资源管理分析

http://blog.csdn.net/sgnyyy/article/details/39268215 原创链接:http://blog.csdn.net/ox_thedarkness/a...
  • anypkv
  • anypkv
  • 2016年10月27日 23:36
  • 688

Unity3D 资源管理 -- 基本概念

1. 资源     1)Shader(着色器)资源:定义物体的表面,与财质配合使用。     2)Compute Shader(可计算着色器)资源:充分利用了DX11的一些特性,可创建非常炫丽的视觉效...
  • MyArrow
  • MyArrow
  • 2015年01月05日 11:43
  • 1453

Unity3D资源管理架构

在Unity3D引擎中,场景资源文件(.unity)是以2进制格式存储的,但同时它也有一种基于文本的表现格式。可在Edit>Project Setting>Editor 中设置: 1.使用bin...
  • sakyaer
  • sakyaer
  • 2015年06月06日 19:01
  • 1988

Unity3d 资源加载与内存管理

 原文链接(一):http://game.ceeger.com/forum/read.php?tid=4394 原文链接(二):http://game.ceeger.com/forum/rea...

Unity5 AssetBundle资源管理架构设计

http://blog.csdn.net/qq_19399235/article/details/51702964 本文参考的AssetBundle技术文章:http://liwei...
  • anypkv
  • anypkv
  • 2016年10月27日 23:46
  • 869

Unity3D资源加载与内存管理

Unity3D资源加载与内存管理 最近网友通过网站搜索Unity3D在手机及其他平台下占用内存太大。这里写下关于Unity3D对于内存的管理与优化。 Unity3D 里有两种动态加载机制:一个是Res...

Unity5 如何做资源管理和增量更新

工具Unity 中的资源来源有三个途径:一个是Unity自动打包资源,一个是Resources,一个是AssetBundle。 Unity自动打包资源是指在Unity场景中直接使用到的资源会随着场景被...
  • ring0hx
  • ring0hx
  • 2015年06月05日 14:40
  • 27805
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Unity3D游戏开发框架-资源管理类ResourceManage
举报原因:
原因补充:

(最多只允许输入30个字)