[Unity3D]ResourceManager类及其编辑器扩展

本文介绍了一种在Unity3D中管理Resources目录资源的方法,通过创建一个名为ResourceManager的单例类,实现了资源的分类、重命名和异步加载功能。该类方便了游戏中动态加载物体,只需将其附加到游戏物体即可使用。
摘要由CSDN通过智能技术生成

为了方便程序中动态加载resources目录中物体,编写了一个ResourceManager的单例类,使用时需要将其附加到一个游戏物体上。

可以实现对物体的分类、重命名、异步加载。

可用方法如下:

//通过名字和类型加载,类型为0时,不判断类型
ResourceRes<T> Load<T>(string name, ResourceType type = 0) where T : UnityEngine.Object

//通过名字和类型加载所有,类型为0时,不判断类型
T[] LoadAll<T>(string name, ResourceType type = 0) where T : UnityEngine.Object

//通过类型加载所有,可以用与的方式,例如加载两个类型:(ResourceType.BGM|ResourceType.Model)
ResourceRes<T>[] LoadAllFromTypeMask<T>(int typeMask) where T : UnityEngine.Object

//异步通过类型加载所有
public void LoadAllFromTypeMaskAsync<T>(int typeMask, Action<ResourceRes<T>[]> onComplete) where T : UnityEngine.Object

//异步通过名字和类型加载所有
void LoadAsync<T>(string name, Action<ResourceRes<T>> onComplete, ResourceType type = 0) where T : UnityEngine.Object

使用方式:

GameObject obj = ResourceManager.Instance.Load<GameObject>("Main").res;

ResourceManager.Instance.LoadAsync<GameObject>("Main", (res) =>
{
    if (res != null)
    {
        GameObject obj = res.res;
    }
});

这里写图片描述

源码如下:

using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;

#if UNITY_EDITOR
using UnityEditor;
using System.IO;
#endif

public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
    private static T _Instance;

    public static T Instance
    {
        get
        {
            if (_Instance == null)
            {
                _Instance = FindObjectOfType<T>();
            }
            return _Instance;
        }
    }
}

//物体分类,一个物体可以是多种类型
public enum ResourceType
{
    BGM = 0x0001,
    Model = 0x0002,
    Scene = 0x0004,
    PromptAudio = 0x0008,
}

[System.Serializable]
public class ResourceItem
{
    public string name;//资源名字
    public string path;//资源resources路径
    public ResourceType type;//资源类型

    public ResourceItem(string name, string path, ResourceType type)
    {
        this.name = name;
        this.path = path;
        this.type = type;
    }
}

[Serializable]
public class ResourceRes<T> where T : UnityEngine.Object
{
    public string
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值