使用cocos creator 3.0 类型分配报错问题
1.使用cocos creator 3.0 类型分配报错问题
详细解决方法:请参考这片文章
https://blog.csdn.net/weixin_38531633/article/details/114874352
前段时间 cocos 突然升级到了 3.0 界面UI 功能都极大地做了优化
脚本还是TS
但是 打开编辑器之后有报错提示:
这里我需要使用Label 类型的时候
把类型限定去掉,分配的默认值必须有 赋值null
@property({ type: Label })
public text = null;
2.使用cocos creator 3.0 赋值表达式的左侧不能是可选属性访问问题
3.使用cocos creator 3.0 对象可能为 “null”。ts(2531)
4.不能将类型“SpriteFrame | null | undefined”分配给类型“SpriteFrame | null”。ts(2322)问题
2、3、4 这种问题 是cocos 3.0 对类型限定极为严格,加强了校验方式。
甚至可以这样写
this.node?.getComponent(Sprite)?.spriteFrame
解决方案:
可以使用 as 以及 赋予初始值的方式
初始值为null 或者直接赋予一个默认值
@property({ type: Label })
public text = null;
//赋值 默认值
@property({ type: Sprite })
public img = this.node.getComponent(Sprite);
loadsp(sp: Sprite) {
resources.load('images/background', SpriteFrame,
(err, asset) ={
sp.spriteFrame = asset as SpriteFrame;
});
}
start() {
//局部变量 赋值 as 类型限定
var image: Sprite = this.node.getComponent(Sprite) as Sprite;
//变更默认值
this.img = this.node.getComponent(Sprite) as Sprite;
this.loadsp(this.img);
this.loadsp(image);
}