动态创建prefab

ccc版本:2.4.3


 onLoad () {
        //动态加载prefab
        cc.resources.load("prefabs/role",cc.Prefab,(e,asset)=>{
            
            if(!e && asset.loaded){
                asset.createNode((e,p)=>{
                if(!e){
                    this.role = p
                    this.tiledObjectLayar = this.node.getChildByName("对象层 1").getComponent(cc.TiledObjectGroup)
                    let o1 = this.tiledObjectLayar.getObject("出生地1")
                    this.node.addChild(this.role)
                    this.role.setPosition(o1.x,o1.y)
                }else{
                    cc.log("角色加载出错")
                }
                
               })
               
            }else{
                cc.log("角色加载出错")
            }
        })
        
    }

cc.resources.load()和文档里的参数不一样,callback的第二个参数是cc.Asset。所以不能用cc.instantiate()创建,我看到cc.Asset对象有个createNode()方法,我加载的资源是一个prefab类型,使用createNode()的时候,报错asset.createNode is not a function,如果这类资源没有相应的节点类型,该方法应该是空的才会报这个错,prefab应该是有节点的吧,怎么会报错呢?我只想动态加载加载prefab(非拖拽)。

createNode()方法vscode的使用提示:

!#en Create a new node using this asset in the scene. If this type of asset dont have its corresponding node type, this method should be null. !#zh 使用该资源在场景中创建一个新节点。 如果这类资源没有相应的节点类型,该方法应该是空的。

任何人都可以回答这个问题!

直接cc.instantiate(asset)就完事了,有什么不能的,返回的类型给你的是基类cc.Asset你就不敢cc.instantiate了吗?,强制转换一下类型ts就不会报错了。

这里给你一个我使用的动态加载的方法

/**
 * 从Bundle中获取资源
 * @param bundleName Bundle名字(resources也是Bundle,加载resources里面的资源也可以将Bundle的名字赋值resources即可)
 * @param assetPath 资源相对路径
 * @param assetType 资源类型
 * @param onComplete 获取后的回调
 */
public getAssetFromBundle(bundleName, assetPath, assetType, onComplete) {
    let bundle = cc.assetManager.getBundle(bundleName);
    let fun = (bundle) => {
        bundle.load(assetPath, assetType, (err, asset) => {
            if (err) {
                console.log(`加载Bundle资源错误!`, assetPath, err);
            } else
                onComplete(asset);
        })
    };
    if (bundle) {
        fun(bundle);
    }
    else {
        cc.assetManager.loadBundle(bundleName, (err, bundle) => {
            if (err) {
                console.log(`加载Bundle错误!`, bundleName, err);
            } else {
                fun(bundle);
            }
        })
    }
}
1赞

强制转换 解决问题了

marks!!

该主题在最后一个回复创建后14天后自动关闭。不再允许新的回复。