Creating a custom PlayClipAtPoint function

  • 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; // This value should be taken from the audio mixer

    private void Start()
    {
        // References
        oneShotAudioParent = GameObject.Find("OneShots");
    }

    public void PlayClipAtPoint(AudioClip clip, Vector2 pos, float pitch)
    {
        // Create new game object
        GameObject oneShotClip = new();
        // Set object position
        oneShotClip.transform.SetParent(oneShotAudioParent.transform);
        oneShotClip.transform.position = pos;
        oneShotClip.transform.localPosition = new Vector3(pos.x, pos.y, 0);

        // Add audio source
        AudioSource oneShotAudioSource = oneShotClip.AddComponent<AudioSource>();
        // Change settings
        oneShotAudioSource.outputAudioMixerGroup = audioMixer;
        oneShotAudioSource.clip = clip;
        oneShotAudioSource.volume = sfxVolume;
        oneShotAudioSource.pitch = pitch;

        // Play audio
        oneShotAudioSource.Play();

        // Destroy after clip ends
        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.