如何访问新建类的自定义属性

学习COCOS CREATOR中,界面里有一个组件(对应SPRITE),我为这个组件对应了一个脚本。
各位所见,脚本中有一个自定义属性type,我想在其他脚本里获取这个对象后,通过其type属性的值做一些判断。

但是在其他脚本获取到对象后,使用对象名.type输出的结果为undefined。用谷歌浏览器输出这个对象,控制台里显示是个cc.Node,里面没有我定义的type属性。

请问我应该怎么做才能在其他脚本里访问到这个对象的属性?

组件的脚本如下:(未完成)

cc.Class({
extends: cc.Component,

properties: {
  
    game: {
        default: null,
        serializable: false
    },
    type:0,
    usingStatus:0,//使用状况,0为不可用,1为可用。
    
},
getType: function () {
    return this.type;
},
// use this for initialization
onLoad: function () {
    cc.log(this.type);
    // this.node.x=20;
    // this.node.y=300;
    // this.setInputControl();
},
fallDown:function(){
    //this.setPosition(this.getPosition().x,this.getPosition().y-1);
    this.node.y=this.node.y-1;
},
setInputControl: function () {
    
},
// called every frame, uncomment this function to activate update callback
update: function (dt) {
    if(this.usingStatus==0){
        return;
    }
    if(this.node.y>-((cc.winSize.height/2)-this.node.width/2)){
        this.fallDown();
    }else{
        this.node.y=300;
        this.usingStatus=0;
    }
   // console.log(this.getComponent('Game'));
},

});

1赞

获取到节点之后还要getComponent()获取该组件,然后.type才能访问到

您能更具体的说明一下吗?是谁调用getComponent(),参数用什么?

你获得的是Node对象,Node本身是没有这个type属性的,这个type属性是在这个node的脚本上,而脚本是一种component,所以需要取到这个node后:

let script = this.node.getComponent('组件脚本名');
script.type;

当然,老写getComponent比较麻烦,如果你是通过properties声明的方式获取这个脚本。那么,只需要在定义的地方把

type: cc.Node
改成
type: require('组件脚本名')

这样取到的直接就是这个脚本,而不是node。

1赞