51 lines
1.3 KiB
TypeScript
51 lines
1.3 KiB
TypeScript
import { _decorator, Node, resources, Prefab, instantiate } from 'cc'
|
|
const { ccclass } = _decorator
|
|
|
|
import { assetManager, Asset } from 'cc'
|
|
|
|
function loadResource<T extends Asset>(path: string, type: new () => T): Promise<T> {
|
|
return new Promise((resolve, reject) => {
|
|
assetManager.resources.load(path, type, (err: Error | null, asset: T) => {
|
|
err ? reject(err) : resolve(asset)
|
|
})
|
|
})
|
|
}
|
|
|
|
@ccclass('prefabOp')
|
|
export class prefabOp {
|
|
// 加载预制体 parent:父节点
|
|
public Load(path: string): Node {
|
|
let instance: Node = null
|
|
resources.load(path, Prefab, (err, prefab) => {
|
|
if (err) {
|
|
console.error(`加载预制体${path}失败:`, err)
|
|
return
|
|
}
|
|
try {
|
|
instance = instantiate(prefab)
|
|
} catch (err) {
|
|
console.error(`初始化预制体${path}失败:`, err)
|
|
}
|
|
})
|
|
return instance
|
|
}
|
|
|
|
// 同步加载版本
|
|
public async LoadAsync(path: string): Promise<Node> {
|
|
try {
|
|
const prefab = await loadResource<Prefab>(path, Prefab)
|
|
const instance = instantiate(prefab)
|
|
return instance
|
|
} catch (err) {
|
|
console.error(`加载预制体${path}失败:`, err)
|
|
}
|
|
}
|
|
|
|
// 释放预制体资源
|
|
public Release(path: string) {
|
|
resources.release(path, Prefab)
|
|
}
|
|
|
|
update(deltaTime: number) {}
|
|
}
|