如何在Properties中获取子节点的Component

例如我在Prefab的脚本里,定义了:

cc.Class(
{
    properties: 
    {
        Text:
        {
            get(){ return this.node.getChildByName( '@label' ).getComponent( cc.Label ).string; },
            set(value){ this.node.getChildByName( '@label' ).getComponent( cc.Label ).string = value; },
        },
    }
}


尝试在properties中取得子节点的Component,
但这样无法运行,编辑器会提示无法从 undefine 中执行 getComponent

有调用栈吗?

1赞

@jare 大神,調用棧在這,

 TypeError: Cannot read property 'getComponent' of null
2
at prefab_Label.get [as string] (/Volumes/App/temp/quick-scripts/assets/scripts/prefabs/prefab@Label.js:17:47)
at dumpByClass (/Applications/Cocos/CocosCreator.app/Contents/Resources/app.asar/editor/page/scene-utils/dump/get-node-dump.js:1:4326)
at dumpNode (/Applications/Cocos/CocosCreator.app/Contents/Resources/app.asar/editor/page/scene-utils/dump/get-node-dump.js:1:6276)
at Object.Editor.getNodeDump (/Applications/Cocos/CocosCreator.app/Contents/Resources/app.asar/editor/page/scene-utils/dump/get-node-dump.js:1:6786)
at Object.dumpNode (/Applications/Cocos/CocosCreator.app/Contents/Resources/app.asar/editor/page/scene-utils/index.js:1:17564)
at editor-scene.scene:query-node (file:///Applications/Cocos/CocosCreator.app/Contents/Resources/app.asar/editor/builtin/scene/panel/scene.js:1:6897)
at Object.Panel._dispatch (/Applications/Cocos/CocosCreator.app/Contents/Resources/app.asar/editor-framework/lib/renderer/panel.js:1:2211)
at EventEmitter.ipcRenderer.on (/Applications/Cocos/CocosCreator.app/Contents/Resources/app.asar/editor-framework/lib/renderer/ipc.js:1:3891)
at emitMany (events.js:127:13)
at EventEmitter.emit (events.js:201:7)

不過我在新項目似乎遇不到,應該是我自已的代碼有問題

我再查查看,感謝您的回覆 :grin:

似乎是属性管理器访问 prefab 数据引起的。试着判断下 this.node.getChildByName( ‘@label’ ) 是否为空吧,为空就不要 getComponent

1赞

打包到手机端 偶尔会 get不到预制体
2019-04-20 12:49:09.478 18448-18519/? E/jswrapper: ERROR: Uncaught TypeError: Cannot read property ‘getComponent’ of null, location: src/cocos2d-jsb.81fc6.js:0:0
STACK:
[0]getComponent@src/cocos2d-jsb.81fc6.js:11463
[1]anonymous@src/project.e2e7c.js:9026
[2]anonymous@src/cocos2d-jsb.81fc6.js:18458
[3]anonymous@src/cocos2d-jsb.81fc6.js:24004
[4]fireTimeout@jsb-adapter/jsb-builtin.js:2033
[5]tick@jsb-adapter/jsb-builtin.js:1995

一直在报这个错

找不到场景下的节点 cc.director.getScene().getChildByName(“club_scene”).addChild(prefabs); 有什么办法解决吗
都是这么写的 应该是获取不到 club_scene