Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Button

Button component. Can be pressed or clicked. Button has 4 Transition types:

  • Button.Transition.NONE // Button will do nothing
  • Button.Transition.COLOR // Button will change target's color
  • Button.Transition.SPRITE // Button will change target Sprite's sprite
  • Button.Transition.SCALE // Button will change target node's scale

The button can bind events (but you must be on the button's node to bind events).
The following events can be triggered on all platforms.

  • cc.Node.EventType.TOUCH_START // Press
  • cc.Node.EventType.TOUCH_MOVE // After pressing and moving
  • cc.Node.EventType.TOUCH_END // After pressing and releasing
  • cc.Node.EventType.TOUCH_CANCEL // Press to cancel

The following events are only triggered on the PC platform:

  • cc.Node.EventType.MOUSE_DOWN
  • cc.Node.EventType.MOUSE_MOVE
  • cc.Node.EventType.MOUSE_ENTER
  • cc.Node.EventType.MOUSE_LEAVE
  • cc.Node.EventType.MOUSE_UP

The developer can get the current clicked node with event.target from event object which is passed as parameter in the callback function of click event.

example
import { log, Node } from 'cc';
// Add an event to the button.
button.node.on(Node.EventType.TOUCH_START, (event) => {
    log("This is a callback after the trigger event");
});
// You could also add a click event
// Note: In this way, you can't get the touch event info, so use it wisely.
button.node.on(Node.EventType.CLICK, (button) => {
   //The event is a custom event, you could get the Button component via first argument
})

Hierarchy

Index

Constructors

Properties

Accessors

Methods

Constructors

constructor

  • newButton(name?: string): Button

Properties

Private __prefab

__prefab: CompPrefabInfo | null = null

Protected _disabledColor

_disabledColor: Color = new Color(124, 124, 124, 255)

Protected _disabledSprite

_disabledSprite: SpriteFrame | null = null

Protected _duration

_duration: number = 0.1

Private _enabled

_enabled: boolean = true

Private _fromColor

_fromColor: Color = new Color()

Private _fromScale

_fromScale: Vec3 = new Vec3()

Protected _hoverColor

_hoverColor: Color = new Color(211, 211, 211, 255)

Protected _hoverSprite

_hoverSprite: SpriteFrame | null = null

Private _hovered

_hovered: boolean = false

Private _id

_id: string = idGenerator.getNewId()

For internal usage.

Protected _interactable

_interactable: boolean = true

Protected _name

_name: string

Protected _normalColor

_normalColor: Color = Color.WHITE.clone()

Protected _normalSprite

_normalSprite: SpriteFrame | null = null

_objFlags

_objFlags: number

Private _originalScale

_originalScale: Vec3 | null = null

Private _pressed

_pressed: boolean = false

Protected _pressedColor

_pressedColor: Color = Color.WHITE.clone()

Protected _pressedSprite

_pressedSprite: SpriteFrame | null = null

Private sceneGetter

sceneGetter: null | (() => RenderScene) = null

Private _sprite

_sprite: Sprite | null = null

Protected _target

_target: Node | null = null

Private _targetScale

_targetScale: Vec3 = new Vec3()

Private _time

_time: number = 0

Private _toColor

_toColor: Color = new Color()

Private _toScale

_toScale: Vec3 = new Vec3()

Protected _transition

_transition: Transition = Transition.NONE

Private _transitionFinished

_transitionFinished: boolean = true

Protected _zoomScale

_zoomScale: number = 1.2

clickEvents

clickEvents: ComponentEventHandler[] = []

If Button is clicked, it will trigger event's handler.

node

node: Node = NullNode

The node this component is attached to. A component is always attached to a node.

example
import { log } from 'cc';
log(comp.node);

Static EventType

EventType: EventType = EventType

Static Transition

Transition: Transition = Transition

Static system

system: null = null

Accessors

scriptAsset

  • get scriptAsset(): null

isOnLoadCalled

  • get isOnLoadCalled(): number

resizeToTarget

  • set resizeToTarget(value: boolean): void

disabledColor

  • get disabledColor(): Readonly<Color>
  • set disabledColor(value: {}): void

disabledSprite

duration

  • get duration(): number
  • set duration(value: number): void

enabled

  • get enabled(): boolean
  • set enabled(value: boolean): void

enabledInHierarchy

  • get enabledInHierarchy(): boolean

hoverColor

  • get hoverColor(): Readonly<Color>
  • set hoverColor(value: {}): void

hoverSprite

interactable

  • get interactable(): boolean
  • set interactable(value: boolean): void
  • Whether the Button is disabled. If true, the Button will trigger event and do transition.

    Returns boolean

  • Whether the Button is disabled. If true, the Button will trigger event and do transition.

    Parameters

    • value: boolean

    Returns void

isValid

  • get isValid(): boolean
  • Indicates whether the object is not yet destroyed. (It will not be available after being destroyed)
    When an object's destroy is called, it is actually destroyed after the end of this frame. So isValid will return false from the next frame, while isValid in the current frame will still be true. If you want to determine whether the current frame has called destroy, use isValid(obj, true), but this is often caused by a particular logical requirements, which is not normally required.

    default

    true

    readonly
    example
    import { Node, log } from 'cc';
    const node = new Node();
    log(node.isValid);    // true
    node.destroy();
    log(node.isValid);    // true, still valid in this frame
    // after a frame...
    log(node.isValid);    // false, destroyed in the end of last frame

    Returns boolean

name

  • get name(): string
  • set name(value: string): void

normalColor

  • get normalColor(): Readonly<Color>
  • set normalColor(value: {}): void

normalSprite

pressedColor

  • get pressedColor(): Readonly<Color>
  • set pressedColor(value: {}): void

pressedSprite

target

  • get target(): Node
  • set target(value: Node): void
  • Transition target.
    When Button state changed:

    • Button.Transition.NONE // Button will do nothing
    • Button.Transition.COLOR // Button will change target's color
    • Button.Transition.SPRITE // Button will change target Sprite's sprite
    • Button.Transition.SCALE // Button will change target node's scale

    Returns Node

  • Transition target.
    When Button state changed:

    • Button.Transition.NONE // Button will do nothing
    • Button.Transition.COLOR // Button will change target's color
    • Button.Transition.SPRITE // Button will change target Sprite's sprite
    • Button.Transition.SCALE // Button will change target node's scale

    Parameters

    Returns void

transition

uuid

  • get uuid(): string

zoomScale

  • get zoomScale(): number
  • set zoomScale(value: number): void
  • When user press the button, the button will zoom to a scale. The final scale of the button equals (button original scale * zoomScale) NOTE: Setting zoomScale less than 1 is not adviced, which could fire the touchCancel event if the touch point is out of touch area after scaling. if you need to do so, you should set target as another background node instead of the button node.

    Returns number

  • When user press the button, the button will zoom to a scale. The final scale of the button equals (button original scale * zoomScale) NOTE: Setting zoomScale less than 1 is not adviced, which could fire the touchCancel event if the touch point is out of touch area after scaling. if you need to do so, you should set target as another background node instead of the button node.

    Parameters

    • value: number

    Returns void

Methods

preload

  • __preload(): void

Protected applyTarget

  • _applyTarget(): void

Protected applyTransition

  • applyTransition(state: string): void

destroyImmediate

  • _destroyImmediate(): void

destruct

  • _destruct(): void
  • Clear all references in the instance.

    NOTE: this method will not clear the getter or setter functions which defined in the instance of CCObject. You can override the _destruct method if you need, for example: _destruct: function () { for (var key in this) { if (this.hasOwnProperty(key)) { switch (typeof this[key]) { case 'string': this[key] = ''; break; case 'object': case 'function': this[key] = null; break; } } }

    Returns void

Protected getButtonState

  • _getButtonState(): string

Optional Private getLocalBounds

  • getLocalBounds(out_rect: Rect): void
  • If the component's bounding box is different from the node's, you can implement this method to supply a custom axis aligned bounding box (AABB), so the editor's scene view can perform hit test properly.

    Parameters

    • out_rect: Rect

      The rect to store the result bounding rect

    Returns void

Private getRenderScene

  • _getRenderScene(): RenderScene

Protected getTargetSprite

  • getTargetSprite(target: Node | null): null | Sprite

instantiate

  • instantiate(cloned: any): any

Protected onMouseMoveIn

Protected onMouseMoveOut

onPreDestroy

  • _onPreDestroy(): void

Private onTargetColorChanged

  • onTargetColorChanged(color: Color): void

Private onTargetSpriteFrameChanged

  • onTargetSpriteFrameChanged(comp: Sprite): void

Private onTargetTransformChanged

  • onTargetTransformChanged(transformBit: TransformBit): void

Protected onTouchBegan

Protected onTouchCancel

Protected onTouchEnded

Protected onTouchMove

Protected registerNodeEvent

  • _registerNodeEvent(): void

Protected registerTargetEvent

  • registerTargetEvent(target: any): void

Protected resetState

  • _resetState(): void

Protected resizeNodeToTargetNode

  • _resizeNodeToTargetNode(): void

Private setCurrentStateColor

  • setCurrentStateColor(color: Color): void

Private setCurrentStateSpriteFrame

  • setCurrentStateSpriteFrame(spriteFrame: SpriteFrame | null): void

Protected unregisterNodeEvent

  • _unregisterNodeEvent(): void

Protected unregisterTargetEvent

  • unregisterTargetEvent(target: any): void

Protected updateColorTransition

  • updateColorTransition(state: string): void

Protected updateScaleTransition

  • updateScaleTransition(state: string): void

Protected updateSpriteTransition

  • updateSpriteTransition(state: string): void

Protected updateState

  • _updateState(): void

Protected zoomBack

  • _zoomBack(): void

Protected zoomUp

  • _zoomUp(): void

addComponent

  • addComponent<T>(classConstructor: Constructor<T>): T | null
  • addComponent(className: string): Component | null

destroy

  • destroy(): boolean

getComponent

  • getComponent<T>(classConstructor: Constructor<T>): T | null
  • getComponent(className: string): Component | null
  • Returns the component of supplied type if the node has one attached, null if it doesn't.
    You can also get component in the node by passing in the name of the script.

    example
    // get custom test calss.
    var test = node.getComponent("Test");

    Type parameters

    Parameters

    • classConstructor: Constructor<T>

      The class of component to be retrieved or to be created

    Returns T | null

  • Returns the component of supplied type if the node has one attached, null if it doesn't.
    You can also get component in the node by passing in the name of the script.

    example
    // get custom test calss.
    var test = node.getComponent("Test");

    Parameters

    • className: string

      A string for the class name of the component

    Returns Component | null

getComponentInChildren

  • getComponentInChildren<T>(classConstructor: Constructor<T>): T | null
  • getComponentInChildren(className: string): Component | null

getComponents

  • getComponents<T>(classConstructor: Constructor<T>): T[]
  • getComponents(className: string): Component[]

getComponentsInChildren

  • getComponentsInChildren<T>(classConstructor: Constructor<T>): T[]
  • getComponentsInChildren(className: string): Component[]

Protected Optional lateUpdate

  • lateUpdate(dt: number): void
  • LateUpdate is called every frame, if the Component is enabled.
    This is a lifecycle method. It may not be implemented in the super class.
    You can only call its super class method inside it. It should not be called manually elsewhere.

    Parameters

    • dt: number

      the delta time in seconds it took to complete the last frame

    Returns void

Protected Optional onDestroy

  • onDestroy(): void
  • Called when this component will be destroyed.
    This is a lifecycle method. It may not be implemented in the super class.
    You can only call its super class method inside it. It should not be called manually elsewhere.

    Returns void

onDisable

  • onDisable(): void

onEnable

  • onEnable(): void

Optional onFocusInEditor

  • onFocusInEditor(): void

Protected Optional onLoad

  • onLoad(): void
  • When attaching to an active node or its node first activated.
    onLoad is always called before any start functions, this allows you to order initialization of scripts.
    This is a lifecycle method. It may not be implemented in the super class.
    You can only call its super class method inside it. It should not be called manually elsewhere.

    Returns void

Optional onLostFocusInEditor

  • onLostFocusInEditor(): void

Protected Optional onRestore

  • onRestore(): void
  • onRestore is called after the user clicks the Reset item in the Inspector's context menu or performs an undo operation on this component.

    If the component contains the "internal state", short for "temporary member variables which not included
    in its CCClass properties", then you may need to implement this function.

    The editor will call the getset accessors of your component to record/restore the component's state
    for undo/redo operation. However, in extreme cases, it may not works well. Then you should implement
    this function to manually synchronize your component's "internal states" with its public properties.
    Once you implement this function, all the getset accessors of your component will not be called when
    the user performs an undo/redo operation. Which means that only the properties with default value
    will be recorded or restored by editor.

    Similarly, the editor may failed to reset your component correctly in extreme cases. Then if you need
    to support the reset menu, you should manually synchronize your component's "internal states" with its
    properties in this function. Once you implement this function, all the getset accessors of your component
    will not be called during reset operation. Which means that only the properties with default value
    will be reset by editor.

    This function is only called in editor mode.

    Returns void

Optional resetInEditor

  • resetInEditor(): void

schedule

  • schedule(callback: any, interval?: number, repeat?: number, delay?: number): void
  • Schedules a custom task.
    If the task is already scheduled, then the interval parameter will be updated without scheduling it again.

    example
    import { log } from 'cc';
    this.schedule((dt) => void log(`time: ${dt}`), 1);

    Parameters

    • callback: any

      The callback function of the task

    • Default value interval: number = 0

      The time interval between each invocation

    • Default value repeat: number = legacyCC.macro.REPEAT_FOREVER

      The repeat count of this task, the task will be invoked (repeat + 1) times, use macro.REPEAT_FOREVER to repeat a task forever

    • Default value delay: number = 0

      The delay time for the first invocation, Unit: s

    Returns void

scheduleOnce

  • scheduleOnce(callback: any, delay?: number): void
  • Schedules a task that runs only once, with a delay of 0 or larger.

    method

    scheduleOnce

    see

    schedule

    example
    import { log } from 'cc';
    this.scheduleOnce((dt) => void log(`time: ${dt}`), 2);

    Parameters

    • callback: any

      The callback function of the task

    • Default value delay: number = 0

      The delay time for the first invocation, Unit: s

    Returns void

Protected Optional start

  • start(): void
  • Called before all scripts' update if the Component is enabled the first time.
    Usually used to initialize some logic which need to be called after all components' onload methods called.
    This is a lifecycle method. It may not be implemented in the super class.
    You can only call its super class method inside it. It should not be called manually elsewhere.

    Returns void

unschedule

  • unschedule(callback_fn: any): void

unscheduleAllCallbacks

  • unscheduleAllCallbacks(): void

update

  • update(dt: number): void

Static deferredDestroy

  • _deferredDestroy(): void

Generated using TypeDoc