Cocos creator-TypeScript基礎宣告

邱繼祥
Will-Cocos Creator
Published in
3 min readJul 8, 2019

參考官方文件,摘要重點

const {ccclass, property} = cc._decorator; //cc._decorator 命名空間中引入ccclassproperty兩個裝飾器

@ccclass //使用裝飾器聲明CCClass
export default class NewClass extends cc.Component { //ES6 Class聲明語法,繼承cc.Component

@property(cc.Label)//使用property裝飾器聲明屬性,括號裡是屬性類型,裝飾器裡的類型聲明主要用於編輯器展示
label: cc.Label = null; //這裡是TypeScript用來聲明變量類型的寫法,冒號後面是屬性類型,等號後面是默認值

//也可以使用完整屬性定義格式
@property({visible: false})
text: string = 'hello';

//成員方法
onLoad() {
// init logic
}
}
@property({type: cc.Integer})
myInteger = 1;
@property
myNumber = 0;

@property
myText = "";
@property(cc.Node)
myNode: cc.Node = null;
@propertymyOffset = new cc.Vec2(100, 100);

型態

@property(cc.Integer) intVar: number = 0; //整數
@property(cc.Float) floatVar: number = 0; //浮點數
@property(cc.Boolean) boolVar: boolean = false; //布林直
@property(cc.Node) nodeVar: cc.Node = null;//節點

宣告陣列

@property([cc.Node])
public myNodes: cc.Node[] = [];
@property([cc.Node])
myNodes: Array<cc.Node> = [];

宣告get、set

@property
_width = 100;

@property
get width () {
return this._width;
}

@property
set width (value) {
cc.log('width changed');
return this._width = value;
}

在 v1.10 包括之後的版本,Creator 對資源類型進行了部分調整。 cc.Texture2D, cc.AudioClip, cc.ParticleAsset 類型數據在 ts 中的聲明一定要按照以下的格式進行聲明:

@property({type: cc.Texture2D})
texture: cc.Texture2D = null;

@property({type: cc.Texture2D})
textures: cc.Texture2D[] = [];

--

--