之前在使用Unity开发的时候,脚本之间相互调用是很常见的,一般可以通过GetComponent方式或者 单例的模式,再或者静态方法的方式去调用其他脚本中的函数 或者变量。
在CocosCreator中我们也可以使用以上的方法去调用其他脚本中的函数。
typescript脚本
1.单例模式
单例脚本
const {ccclass, property} = cc._decorator;
@ccclass
export default class Singleton extends cc.Component {
static readonly instance:Singleton=new Singleton();
testA()
{
console.log("hello");
}
}
这样写只能在这个变量声明的后面直接给instance赋值一次,不能在onLoad里面赋值。好处是单例只会被new和赋值一次。
测试脚本:
const {ccclass, property} = cc._decorator;
import Singleton from './Singleton';
@ccclass
export default class Hello extends cc.Component
{
onLoad()
{
Singleton.instance.testA();
}
2.通过Getcomponent 方式
脚本在主相机上挂着
const {ccclass, property} = cc._decorator;
import Singleton from './Singleton';
@ccclass
export default class Hello extends cc.Component
{
@property (cc.Label)
lable1:cc.Label=null;
onLoad()
{
let scr=cc.find('Canvas/Main Camera').getComponent(Singleton);
scr.testA();
}
}