cocosCreator 之 Button

版本: 3.4.0

参考:Button组件


简介


Button组件主要用于响应用户的点击操作,属性检查器中的示意图:
请添加图片描述

Button组件的主要属性有:

  • Interactable 表示按钮是否可交互,如果未勾选表示禁用
  • Transition表示按钮状态变化的类型,支持图片,缩放,颜色的变化
  • ClickEvents 表示按钮的点击事件回调相关,默认为空

Button组件上的Sprite组件有个属性叫做Grayscale可将按钮图片置灰,如果按钮不包含子节点相关,在脚本中使用:

onLoad() {
  // 获取节点下的Sprite组件,将其设置置灰
  this.node.getComponent(Sprite).grayscale = false;
  // 获取节点下的Button组件,将其设置为禁用
  this.node.getComponent(Button).interactable = false;
}

如果按钮节点包含不同类型的子节点相关,该置灰效果就会有问题。


基本使用


在脚本中使用按钮组件,一般通过 @property(Button) 来获取按钮组件,它的常用情况有:

import { _decorator, Button, Component, Label, Node, Vec3 } from 'cc';
const { ccclass, executeInEditMode, property } = _decorator;
 
@ccclass('UI_DemoLayer')
@executeInEditMode(true)
export class UI_DemoLayer extends Component {
  @property(Button)
  btn: Button = null;

  protected onLoad(): void {
    // 设置按钮的交互
    this.btn.interactable = true;
    // 设置按钮的标题,先获取按钮的子节点,然后获取子节点下的文本组件
    let titleNode = this.btn.node.getChildByName("Label");
    titleNode.getComponent(Label).string = "按钮";
  } 

  protected onEnable(): void {
    // 点击事件回调
    this.btn.node.on(Button.EventType.CLICK, this.clickEvent, this);
  }

  protected onDisable(): void {
    this.btn.node.off(Button.EventType.CLICK, this.clickEvent, this);
  }

  // 参数返回的是button的node属性相关
  private clickEvent(button:Button) {
    console.log(button);
  }
}

针对于点击事件注册相关建议放到onEnableonDisable中。

点击事件的处理也可以在编译器的ClickEvents中添加,可设置为1,然后设置:

  • Target 带脚本组件的节点
  • Component 脚本组件名称
  • Handler 脚本组件的回调方法,该方法必须为public
  • customEventData 自定义字符串相关

请添加图片描述

export class UI_DemoLayer extends Component {
  // 返回的是eventTouch对象和自定义数据
  public ClickCloseEvent(event:any, customData: string) {
    console.log(event)
    console.log(customData)
  }
}

点击音效

按钮的点击需要支持播放音效, 这个主要来通过AudioSource组件的方法playOneShot来实现。

对于音乐音效的播放,一般会封装一个管理类来使用,可参考cocosCreator笔记 之背景音乐

在此不一一罗列,关于点击音效的实现:

export class audioManager {
  // 播放音效(音效名字,指定音量倍数)
  public playSound(name: string, volumeScale: number = 1) {
    resources.load("prefab/sound/" + name, AudioClip, (err, clip) =>{
      if(err) {
        warn("load audioClip failed:" + err);
        return;
      }
      // 音量的大小限制在[0,1]之间
      let volume = clamp01(this._musicVolme * volumeScale);
      this._audioSource.playOneShot(clip, volume);
    });
  }
}

在指定按钮点击事件中,可以调用音效的播放

import { audioManager } from '../manager/audioManager';

export class Adapter_Btn extends Component {
  public ClickCloseEvent(event:any, customData: string) {
		audioManager.instance.playSound("click");
  }
}

拓展

在项目中使用按钮,更多的时候我们希望按钮支持是否禁止快速点击,是否置灰,是否播放特定的音效名。我们可以创建一个按钮适配器的组件来帮助我们实现这些。

如下代码参考于cocosCreator编译器内的项目案例:快上车

import { _decorator, Button, Color, Component, Sprite } from 'cc';
const { ccclass, property, requireComponent } = _decorator;
import { audioManager } from '../manager/audioManager';

@ccclass('Adapter_Btn')
// 指定当前组件依赖的组件,默认为null; 
// 如果当前依赖的组件不存在,引擎会自动将依赖组件添加到同一个节点上,防止脚本出错
@requireComponent(Button)
export class Adapter_Btn extends Component {
    @property({tooltip: "是否播放点击音效"})
    isPlaySound = true;
    @property({tooltip: "音效名"})
    soundName = "click";
    @property({tooltip: "是否禁止快速点击"})
    isForbidQuickClick = true;
    @property({tooltip: "快速点击后,按钮是否置灰,按钮节点需要包含Sprite组件"})
    isNeedGray = true;
    @property({tooltip: "快速点击间隔秒数"})
    onceTime = 0.5;

    private _button: Button = null;             // 按钮组件
    
    protected onLoad(): void {
        this._button = this.node.getComponent(Button);
    }

    protected onEnable(): void {
        this.node.on(Button.EventType.CLICK, this._clickBtnEvent, this);
    }

    protected onDisable(): void {
        this.node.off(Button.EventType.CLICK, this._clickBtnEvent, this);
    }

    private _clickBtnEvent() {
        // 检测是否快速点击
        if (this.isForbidQuickClick) {
            this._button.interactable = false;
          	// 如果是快速点击,设置间隔时间
            this.scheduleOnce(() => {
                if (this._button.node) {
                    this._button.interactable = true;
                }
            }, this.onceTime);
        }

        // 音效相关
        if (this.isPlaySound && (this.soundName.length > 0)) {
            audioManager.instance.playSound(this.soundName);
        }
    }
}

该脚本组件挂载到对应的Button组件下即可,需要注意的是:该组件不会影响到其他脚本组件的按钮点击事件相关,相当于各司其职,互不干涉。


End

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鹤九日

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值