ResourcesManager.cs 1.81 KB
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using UnityEngine.Events;

public class ResourcesManager : Singleton<ResourcesManager>
{
    // 资源缓存字典
    private Dictionary<string, UnityEngine.Object> resourceCache = new Dictionary<string, UnityEngine.Object>();


    /// <summary>
    /// 同步加载资源
    /// </summary>
    /// <typeparam name="T">资源类型</typeparam>
    /// <param name="path">资源路径</param>
    /// <param name="cache">是否缓存</param>
    /// <returns>加载的资源</returns>
    public T Load<T>(string path, bool cache = false) where T : UnityEngine.Object
    {
        if (string.IsNullOrEmpty(path))
        {
            Debug.LogError("资源路径不能为空");
            return null;
        }

        // 检查缓存
        if (resourceCache.TryGetValue(path, out UnityEngine.Object cachedResource))
        {
            return cachedResource as T;
        }

        // 从Resources加载
        T resource = Resources.Load<T>(path);
        if (resource == null)
        {
            Debug.LogError($"无法加载资源: {path}");
            return null;
        }

        // 缓存资源
        if (cache)
        {
            resourceCache[path] = resource;
        }

        return resource;
    }

    /// <summary>
    /// 加载一个二级UI
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public void ShowSecondUI<T>(string path) where T : UIBase
    {
        var uiname = typeof(T).Name;
        if (UIManager.Instance.GetUi<T>() == null)
        {
            var obj = Load<GameObject>(path);
            Instantiate(obj);
            UIManager.Instance.ShowUI<T>();
        }
        else
        {
            Debug.LogError("场景中已经存在相同的UI:  " + uiname);
        }
    }
}