UGUI 扩展 —— 按钮声音组件

之前用NGUI的时候,里面有很多扩展功能很实用,但现在使用UGUI有很多功能需要自己扩展,以便项目使用,今天就简单介绍一下自己扩展的一个给按钮添加声音组件的功能,其实很简单直接上代码吧!

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayUIButtonSound : MonoBehaviour
{
    public enum Trigger
    {
        OnClick,
        OnMouseOver,
        OnMouseOut,
    }
    public AudioClip audioClip;
    public Trigger trigger = Trigger.OnClick;

    public static float Volume;
    [Range(0f, 1f)]
    public float volume = 1;
    [Range(0f, 3f)]
    public float pith = 1;
    void Start()
    {
        if (trigger == Trigger.OnClick)
            EventTriggerListener.Get(gameObject).onClick = OnClick;
        if (trigger == Trigger.OnMouseOver)
            EventTriggerListener.Get(gameObject).onEnter = OnMouseOver;
        if (trigger == Trigger.OnMouseOut)
            EventTriggerListener.Get(gameObject).onExit = OnMouseOut;
    }

    bool canPlay
    {
        get
        {
            if (!enabled)
            {
                return false;
            }
            Button btn = GetComponent<Button>();
            return btn == null;
        }
    }

    void Update()
    {
        if (!Volume.Equals(volume))
        {
            volume = Volume;
        }
    }
    void OnClick(GameObject go)
    {
        if (trigger == Trigger.OnClick)
        {
            UGUITools.PlaySound(audioClip, volume, pith);
        }
    }

    void OnMouseOver(GameObject go)
    {
        if (trigger == Trigger.OnMouseOver)
        {
            UGUITools.PlaySound(audioClip, volume, pith);
        }
    }

    void OnMouseOut(GameObject go)
    {
        if (trigger == Trigger.OnMouseOut)
        {
            UGUITools.PlaySound(audioClip, volume, pith);
        }
    }
}
using UnityEngine;
using System.Collections;

public static class UGUITools
{
    static AudioSource audioSource;
    public static AudioSource PlaySound(AudioClip clip, float volume, float pitch)
    {
        if (clip == null)
        {
            throw new System.Exception("此对象为空");
        }
        if (!audioSource)
        {
            Camera cam = Camera.main;
            audioSource = cam.GetComponent<AudioSource>();
            if (audioSource == null)
            {
                audioSource = cam.gameObject.AddComponent<AudioSource>();
            }
        }
        audioSource.priority = 50;
        audioSource.pitch = pitch;
        audioSource.volume = volume;
        audioSource.clip = clip;
        audioSource.Play();
        return audioSource;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值