Skip to content

Instantly share code, notes, and snippets.

@aDu
Last active July 3, 2020 01:06
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 aDu/d57b923c96f242e28fe029f3980c5123 to your computer and use it in GitHub Desktop.
Save aDu/d57b923c96f242e28fe029f3980c5123 to your computer and use it in GitHub Desktop.
Unity3D Sound Zone - Collider2D instead of point audio source (because Unity only supports audio coming from a single point or circle, instead of coming from a custom shape). AudioSource will move as close to the player as possible but keeping inside the collider. Please modify it to suit your use-cases (modify the Player.Instance and AudioMgr.I…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 2D Sound Zone.
// Recommended AudioSource settings: Spatial Blend: 3D. Doppler Level, Spread and reverb zone mix set to 0.
// AudioSource will move as close to the player as possible, but will stay within the collider.
// Only works with only one Collider2D component.
// https://gist.github.com/aDu/d57b923c96f242e28fe029f3980c5123
public class SoundZone : MonoBehaviour
{
public AudioSource audioSource; // Audio Source must be in a child object and not itself, otherwise the collider will also move.
private Collider2D col;
private void Awake() {
col = GetComponent<Collider2D>();
}
private void Update() {
audioSource.transform.position = col.ClosestPoint(AudioMgr.Instance.AudioListener.transform.position);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment