58 lines
1.4 KiB
C#
58 lines
1.4 KiB
C#
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.Audio;
|
|
|
|
namespace OHM.UnityToolkit
|
|
{
|
|
[Serializable]
|
|
public class SFX
|
|
{
|
|
public SFXInstance customPrefab;
|
|
|
|
public AudioClip clip;
|
|
|
|
public AudioMixerGroup group;
|
|
|
|
public SFXInstance Play(Transform parent)
|
|
{
|
|
if (customPrefab == null && clip == null)
|
|
{
|
|
return null;
|
|
}
|
|
SFXInstance instance = Instanciate(parent);
|
|
if (instance.audioSource != null)
|
|
{
|
|
instance.audioSource.clip = clip;
|
|
}
|
|
if (group != null)
|
|
{
|
|
instance.audioSource.outputAudioMixerGroup = group;
|
|
}
|
|
instance.name = ((instance.audioSource.clip != null) ? ("SFX_" + instance.audioSource.clip.name) : "SFX_noclip");
|
|
instance.audioSource.Play();
|
|
return instance;
|
|
}
|
|
|
|
private SFXInstance Instanciate(Transform parent)
|
|
{
|
|
SFXInstance prefab = ((customPrefab != null) ? customPrefab : createDefaultInstance());
|
|
SFXInstance instance = UnityEngine.Object.Instantiate(prefab);
|
|
instance.gameObject.transform.parent = parent;
|
|
instance.gameObject.transform.localPosition = Vector3.zero;
|
|
return instance;
|
|
}
|
|
|
|
private SFXInstance createDefaultInstance()
|
|
{
|
|
var go = new GameObject();
|
|
AudioSource source = go.AddComponent<AudioSource>();
|
|
source.spatialBlend = 0f;
|
|
source.playOnAwake = true;
|
|
SFXInstance instance = go.AddComponent<SFXInstance>();
|
|
instance.autoDestroyOnEnd = true;
|
|
return instance;
|
|
}
|
|
|
|
}
|
|
}
|