ResUtils.ts
2.59 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
70
71
72
73
74
75
76
77
78
79
export namespace ResUtils {
export async function loadRes<T extends cc.Asset>(resource: string, type: new () => T, maxTryCount = 3): Promise<T> {
return new Promise((resolve, reject) => {
let tryCount = 0;
function loadFunc() {
tryCount++;
cc.resources.load(resource, type as any, (err: Error, res: any) => {
if (err) {
if (tryCount < maxTryCount) {
setTimeout(() => {
loadFunc();
}, 500);
} else {
reject(err);
}
} else {
if (res.json) {
resolve(res.json);
} else if (res.text) {
resolve(res.text);
} else {
resolve(res);
}
}
});
}
loadFunc();
});
}
//动态加载图片的方法
export async function loadOnlineImg(container: cc.Sprite, url: string): Promise<any> {
return new Promise<any>((resolve, reject) => {
cc.assetManager.loadRemote(url, function (err, texture) {
if (err) {
reject(err)
} else {
var sprite = new cc.SpriteFrame(texture);
container.spriteFrame = sprite;
resolve()
}
});
})
}
/**释放资源 */
export function releaseRes(resource: string) {
cc.resources.release(resource)
}
/**批量释放资源 */
export function releaseResArray(resources: string[]) {
for (let i = 0; i < resources.length; i++) {
cc.resources.release(resources[i])
}
}
export function releaseAsset(asset: cc.Asset) {
cc.assetManager.releaseAsset(asset)
}
export function releaseAssetArray(assets: cc.Asset[]) {
assets.forEach((asset) => cc.assetManager.releaseAsset(asset));
}
/**加载预制体并实例化node */
export async function createWithPrefab(resource: string): Promise<cc.Node> {
let prefab = await ResUtils.loadRes<cc.Prefab>(resource, cc.Prefab);
if (!prefab) throw new Error("Load prefab failed!");
let node = cc.instantiate(prefab);
if (node) {
return node;
} else {
throw new Error("Instantiate node failed!");
}
}
//检
}