使用常驻节点传参一直不成功

export class gameController extends Component {

id = 0;

onLoad() {

    game.addPersistRootNode(this.node);

}

set levelID(value){

    this.id = value;

}

常驻节点datanode里挂了一个set代码
changeScene(event,customEventData) {

    director.loadScene('gameMenu',this.onSceneLaunched)

}

onSceneLaunched(){

    let a = find('dataNode').getComponent('gameController')

    a.setId(this.id)

    a.setTitle(this.title)

    console.log(a)

}

在另一个按钮下的脚本点击事件中一直报错,报错如下
Uncaught TypeError: Cannot read property ‘id’ of undefined
当吧this.id修改成1的时候报错如下
Uncaught TypeError: a.setId is not a function
一直解决不掉不知道是什么原因,另一个地方调用明明是可以成功的
game.addPersistRootNode(this.node);顺便一提,vscode提示已经被废弃,但是也没找到替代品

弃用game 改用 director.addPersistRootNode(this.node)

id找不到是因为js特性,引用函数会导致this丢失,用
director.loadScene(‘gameMenu’,this.onSceneLaunched.bind(this) 试试

Uncaught TypeError: a.setId is not a function 是对象a里头没有这个方法

…使用常驻节点传参也太麻烦了吧 :joy:申明一个全局单例就可以了啊image 最起码这样做吧。

直接 window.prop = 0,哪里都能用

确实可以,但这样的编码习惯不规范也不安全。

感谢各位大神的回复!我赶紧试试

但是在a里,也就是gameController这个脚本里面我是定义了这个方法的

有个问题请问一下,全局单例的脚本需要挂载吗

不需要,我的例子就说明了这个问题,没有挂载就可以使用,在任何地方都可以直接这么用。