ResourcesManager.cs
1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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);
}
}
}