Skip to content

Instantly share code, notes, and snippets.

@mao-test-h
Last active August 4, 2018 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mao-test-h/e17815702b3f222a449743757203e006 to your computer and use it in GitHub Desktop.
Save mao-test-h/e17815702b3f222a449743757203e006 to your computer and use it in GitHub Desktop.
Unity用SoundCue(っぽいもの)サンプル
namespace MainContents.AudioUtility
{
using UnityEngine;
// UE4のSoundCueを参考にしたもの。
// 内容的にはAudioClipのラッパー的な立ち位置で、AudioClipを取得する際の振る舞いを実装するもの。
// →例 : ランダムでClipを返すもの、配列に登録したClipを順番に取得など。
// ※本当はinterfaceにしたいけどSerializeFieldで登録する都合上、敢えて基底クラスとする...
public abstract class AudioCue : ScriptableObject
{
public abstract AudioClip GetClip();
}
// オーディオキュー用の定義
public sealed class AudioCueConstants
{
public const string MenuPrefix = "AudioCue/";
}
/// <summary>
/// オーディオキュー管理クラス
/// </summary>
public sealed class AudioCueManager : MonoBehaviour
{
// キューのタイプ
public enum CueType
{
Normal = 0,
Random,
}
[SerializeField] AudioSource _source;
[SerializeField] AudioCue[] _audioCues;
public void Play(CueType type, bool isLoop = false)
{
this._source.loop = isLoop;
this._source.clip = this._audioCues[(int)type].GetClip();
this._source.Play();
}
public void PlayOneShot(CueType type, float volumeScale = 1f)
{
this._source.PlayOneShot(this._audioCues[(int)type].GetClip(), volumeScale);
}
public void PlayTest(int type)
{
this.Play((CueType)type);
}
public void PlayTest2(int type)
{
this.PlayOneShot((CueType)type);
}
}
}
// オーディオキューの実装サンプル
namespace MainContents.AudioUtility.Cues
{
using UnityEngine;
/// <summary>
/// 1つのクリップを再生
/// </summary>
[CreateAssetMenu(fileName = "NormalCue", menuName = AudioCueConstants.MenuPrefix + "Normal")]
public sealed class NormalCue : AudioCue
{
[SerializeField] AudioClip _clip;
public override AudioClip GetClip() { return this._clip; }
}
/// <summary>
/// ランダムにClipを返す
/// </summary>
[CreateAssetMenu(fileName = "RandomCue", menuName = AudioCueConstants.MenuPrefix + "Random")]
public sealed class RandomCue : AudioCue
{
[SerializeField] AudioClip[] _clips;
[SerializeField] bool _isNotRepetition = false; // trueなら重複防止
int _currentIndex = -1;
public override AudioClip GetClip()
{
int index = Random.Range(0, this._clips.Length);
AudioClip clip = null;
if (this._isNotRepetition)
{
while (this._currentIndex == index)
{
index = Random.Range(0, this._clips.Length);
}
clip = this._clips[index];
}
else
{
clip = this._clips[index];
}
this._currentIndex = index;
return clip;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment