Frontend/Cocos Creator

[Cocos Creator] Decorator 사용하기

에반황 2018. 1. 4. 16:21


이 글은 PC 버전 TISTORY에 최적화 되어있습니다.


Module _decorator 이해하기

Cocos Creator는 타입스크립트 Decorator를 'cc._decorator'를 통해서 접근할 수 있습니다. Cocos Creator는 Typescript 언어를 기반으로 하고 있기 때문에, Typescript의 Decorator 작동 방식으로 이해하시면 됩니다. 즉 Decorate Func를 통해서 클래스, 메소드, 프로퍼티 그리고 파라미터를 꾸며주는 기능입니다.

Methods

ccclass 
( 
  • [name ] 
)

기존 ES6 Class를 CCClass를 통해서 선언할 수 있습니다. 더 자세한 사항은 Class를 봐주세요. 

nametypedescription
name optionalString

The class name used for serialization. (

examples:

const {ccclass} = cc._decorator;

// define a CCClass, omit the name
@ccclass
class NewScript extends cc.Component {
    // ...
}

// define a CCClass with a name
@ccclass('LoginData')
class LoginData {
    // ...
}

property 
( 
  • [options ] 
)

Class를 위한 프로퍼티를 선언합니다.

nametypedescription
options optionalObject

an object with some property attributes

examples:

const {ccclass, property} = cc._decorator;

@ccclass
class NewScript extends cc.Component {
    @property({
        type: cc.Node
    })
    targetNode1 = null;

    @property(cc.Node)
    targetNode2 = null;

    @property(cc.Button)
    targetButton = null;

    @property
    _width = 100;

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

    @property
    set width (value) {
        return this._width = value;
    }

    @property
    offset = new cc.Vec2(100, 100);

    @property(cc.Vec2)
    offsets = [];

    @property(cc.Texture2D)
    texture = "";
}

// above is equivalent to (上面的代码相当于):

var NewScript = cc.Class({
    properties: {
        targetNode1: {
            default: null,
            type: cc.Node
        },

        targetNode2: {
            default: null,
            type: cc.Node
        },

        targetButton: {
            default: null,
            type: cc.Button
        },

        _width: 100,

        width: {
            get () {
                return this._width;
            },
            set (value) {
                this._width = value;
            }
        },

        texture: {
            default: "",
            url: cc.Texture2D
        },
    }
});

executeInEditMode ( )

Component를 상속받은 CCClass를 Edit Mode에서 작동하게 합니다. 기본적으로는, 모든 컴포넌트는 Play Mode에서만 동작합니다. 그건 콜백 함수들이 Editor 모드에서는 동작하지 않는다는 것입니다. (Editor에서도 동작하도록 ex) 자석모드)

examples:

const {ccclass, executeInEditMode} = cc._decorator;

@ccclass
@executeInEditMode
class NewScript extends cc.Component {
    // ...
}

requireComponent 
( 
  • requiredComponent 
)

Automatically add required component as a dependency for the CCClass that inherit from component. 자동으로 CCClass에 의존관계가 있고, 컴포넌트를 상속한 컴포넌트를 추가해줍니다.

nametypedescription
requiredComponentComponent

examples:

const {ccclass, requireComponent} = cc._decorator;

@ccclass
@requireComponent(cc.Sprite)
class SpriteCtrl extends cc.Component {
    // ...
}


필요로하는 컴포넌트가 없으면 추가해준다.



menu 
( 
  • path 
)

에디터의 'Component' 메뉴에 컴포넌트를 Path를 통해서 등록하게 해줍니다.

nametypedescription
pathString

The path is the menu represented like a pathname. For example the menu could be "Rendering/CameraCtrl".

examples:

const {ccclass, menu} = cc._decorator;

@ccclass
@menu("Rendering/CameraCtrl")
class NewScript extends cc.Component {
    // ...
}



다음과 같이 menu Decorator를 붙인 클래스는 에디터의 컴포넌트 메뉴에서 찾을 수 있게됨



executionOrder (order)

Component의 생명주기 메소드의 실행 순서를 정함. 0보다 작으면 이전에 실행되고, 0보다 크면 이후에 실행됩니다. order는 onLoad, onEnable, start, update, lateUpdate에만 적용되고, onDisable, onDestroy에는 적용되지 않습니다.

nametypedescription
orderNumber

The execution order of lifecycle methods for Component. Those less than 0 will execute before while those greater than 0 will execute after.

examples:

const {ccclass, executionOrder} = cc._decorator;

@ccclass
@executionOrder(1)
class CameraCtrl extends cc.Component {
    // ...
}

disallowMultiple ( )

같은 타입이나 하위 타입의 컴포넌트를 한번 이상 추가하지 못하게 제한합니다.

examples:

const {ccclass, disallowMultiple} = cc._decorator;

@ccclass
@disallowMultiple
class CameraCtrl extends cc.Component {
    // ...
}

playOnFocus ( )

이 장식자를 지정하는 경우 Editor에서 노드를 선택했을 때 60fps로 계속 업데이트 되며, 그렇지 않으면 필요할 때만 update됩니다. 이 속성은 executeInEditMode가 true일 때만 사용 가능합니다.

examples:

const {ccclass, playOnFocus, executeInEditMode} = cc._decorator;

@ccclass
@executeInEditMode
@playOnFocus
class CameraCtrl extends cc.Component {
    // ...
}

inspector 
( 
  • url 
)

url에 명시된 custom html을 컴포넌트 Properties안의 구성요소를 그릴 커스텀 html url을 명시

nametypedescription
urlString

examples:

const {ccclass, inspector} = cc._decorator;

@ccclass
@inspector("packages://inspector/inspectors/comps/camera-ctrl.js")
class NewScript extends cc.Component {
    // ...
}

help 
( 
  • url 
)

커스텀 문서 URL.

nametypedescription
urlString

examples:

const {ccclass, help} = cc._decorator;

@ccclass
@help("app://docs/html/components/spine.html")
class NewScript extends cc.Component {
    // ...
}


Doucment에 대한 Help URL 등록됨 저 버튼을 통해 클릭하면 지정한 URL로 넘어갑니다.







mixins 
( 
  • ctor 
)

NOTE:
The old mixins implemented in cc.Class(ES5) behaves exact the same as multiple inheritance. But since ES6, class constructor can't be function-called and class methods become non-enumerable, so we can not mix in ES6 Classes.
See:
https://esdiscuss.org/topic/traits-are-now-impossible-in-es6-until-es7-since-rev32
One possible solution (but IDE unfriendly):
http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes

NOTE:
You must manually call mixins constructor, this is different from cc.Class(ES5).

nametypedescription
ctorFunction

constructors to mix, only support ES5 constructors or classes defined by using cc.Class, not support ES6 Classes.

examples:

const {ccclass, mixins} = cc._decorator;

class Animal { ... }

const Fly = cc.Class({
    constructor () { ... }
});

@ccclass
@mixins(cc.EventTarget, Fly)
class Bird extends Animal {
    constructor () {
        super();

        // You must manually call mixins constructor, this is different from cc.Class(ES5)
        cc.EventTarget.call(this);
        Fly.call(this);
    }
    // ...
}


반응형