使用cocos creator 3.0 类型分配报错,赋值表达式,对象可能为 “null“,等问题

使用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);
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值