一个简单的组件脚本。html
cc.Class({ extends: cc.Component, properties: { }, // use this for initialization onLoad: function () { }, // called every frame, uncomment this function to activate update callback update: function (dt) { }, });
经过在组件脚本中声明属性,咱们能够将脚本组件中的字段可视化地展现在 属性检查器 中,从而方便地在场景中调整属性值。函数
要声明属性,仅须要在 cc.Class 定义的 properties
字段中,填写属性名字和属性参数便可,在属性检查器中方便查看修改。this
编写这些脚本的用处:这些代码就是编写一个组件(脚本)所需的结构。具备这样结构的脚本就是 Cocos Creator 中的 组件(Component),他们可以挂载到场景中的节点上,提供控制节点的各类功能。例如:例子中的Player控制小怪物弹跳,Game产生星星。spa
完整声明:code
properties: { score: { default: 0, displayName: "Score (player)", tooltip: "The score of player", } }
以上代码为 score
属性设置了三个参数 default
, displayName
和 tooltip
。这几个参数分别指定了 score
的默认值为 0,在 属性检查器 里,其属性名将显示为:“Score (player)”,而且当鼠标移到参数上时,显示对应的 Tooltip。htm
下面是type,displayName等的属性参数:http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.htmlip
这些参数控制了属性在 属性检查器 中的显示方式,以及属性在场景序列化过程当中的行为。get
type 参数it
当 default
不能提供足够详细的类型信息时,为了能在 属性检查器 显示正确的输入控件,就要用 type
显式声明具体的类型:io
当默认值为 null 时,将 type 设置为指定类型的构造函数,这样 属性检查器 才知道应该显示一个 Node 控件。
enemy: { default: null, type: cc.Node }
当默认值为数值(number)类型时,将 type 设置为 cc.Integer
,用来表示这是一个整数,这样属性在 属性检查器 里就不能输入小数点。
score: { default: 0, type: cc.Integer }
当默认值是一个枚举(cc.Enum
)时,因为枚举值自己其实也是一个数字(number),因此要将 type 设置为枚举类型,才能在 属性检查器 中显示为枚举下拉框。
wrap: { default: Texture.WrapMode.Clamp, type: Texture.WrapMode }