- The AudioSource.PlayClipAtPoint() function doesn't let us have a lot of control over the Audio Source itself. So I created a custom class for this.
using UnityEngine;
using UnityEngine.Audio;
public class AudioClipPlayer : MonoBehaviour
{
[Header("Assets")]
[SerializeField] private AudioMixerGroup audioMixer;
[Header("Game Objects")]
[SerializeField] GameObject oneShotAudioParent;
[Header("Variables")]
private float sfxVolume = 0.5f;
private void Start()
{
oneShotAudioParent = GameObject.Find("OneShots");
}
public void PlayClipAtPoint(AudioClip clip, Vector2 pos, float pitch)
{
GameObject oneShotClip = new();
oneShotClip.transform.SetParent(oneShotAudioParent.transform);
oneShotClip.transform.position = pos;
oneShotClip.transform.localPosition = new Vector3(pos.x, pos.y, 0);
AudioSource oneShotAudioSource = oneShotClip.AddComponent<AudioSource>();
oneShotAudioSource.outputAudioMixerGroup = audioMixer;
oneShotAudioSource.clip = clip;
oneShotAudioSource.volume = sfxVolume;
oneShotAudioSource.pitch = pitch;
oneShotAudioSource.Play();
Destroy(oneShotClip, clip.length);
}
}
- This way, you get to control the AudioSource of the clip that you're playing. You can add more customization as you like.