之前用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;
}
}