这是第一个 Unity 开放项目的repo,是 Unity 和社区合作创建的一个小型开源游戏演示,第一款游戏是一款名为 Chop Chop 的动作冒险游戏。
您最多选择25个主题 主题必须以中文或者字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

94 行
2.0 KiB

using System.Collections;
using UnityEngine;
using UnityEngine.Events;
[RequireComponent(typeof(AudioSource))]
public class SoundEmitter : MonoBehaviour
{
private AudioSource _audioSource;
public event UnityAction<SoundEmitter> OnSoundFinishedPlaying;
private void Awake()
{
_audioSource = this.GetComponent<AudioSource>();
_audioSource.playOnAwake = false;
}
/// <summary>
/// Instructs the AudioSource to play a single clip, with optional looping, in a position in 3D space.
/// </summary>
/// <param name="clip"></param>
/// <param name="settings"></param>
/// <param name="hasToLoop"></param>
/// <param name="position"></param>
public void PlayAudioClip(AudioClip clip, AudioConfigurationSO settings, bool hasToLoop, Vector3 position = default)
{
_audioSource.clip = clip;
settings.ApplyTo(_audioSource);
_audioSource.transform.position = position;
_audioSource.loop = hasToLoop;
_audioSource.Play();
if (!hasToLoop)
{
StartCoroutine(FinishedPlaying(clip.length));
}
}
/// <summary>
/// Used when the game is unpaused, to pick up SFX from where they left.
/// </summary>
public void Resume()
{
_audioSource.Play();
}
/// <summary>
/// Used when the game is paused.
/// </summary>
public void Pause()
{
_audioSource.Pause();
}
/// <summary>
/// Used when the SFX finished playing. Called by the <c>AudioManager</c>.
/// </summary>
public void Stop() // Redundant?
{
_audioSource.Stop();
}
public void Finish()
{
if (_audioSource.loop)
{
_audioSource.loop = false;
float timeRemaining = _audioSource.clip.length - _audioSource.time;
StartCoroutine(FinishedPlaying(timeRemaining));
}
}
public bool IsInUse()
{
return _audioSource.isPlaying;
}
public bool IsLooping()
{
return _audioSource.loop;
}
public bool IsFinishing()
{
return !_audioSource.loop;
}
IEnumerator FinishedPlaying(float clipLength)
{
yield return new WaitForSeconds(clipLength);
OnSoundFinishedPlaying.Invoke(this); // The AudioManager will pick this up
}
}