using UnityEngine;
using System.Collections;
public class Foo : MonoBehaviour {
public AudioClip clip;
void Start() {
AudioSource.PlayClipAtPoint (clip, transform.position, 0.1f);
gameObject.SetActive (false);
Debug.Break();
}
}
By calling Debug.Break(), you can pause the game after the current frame. This lets you mess around in the editor a bit. You should see a new object named “One shot audio” in the scene. You can take a look at its properties, or even change them.
By default, the temporary AudioSource has a logarithmic sound falloff. If my camera is 10 units away from the audio, we’re already hearing it at about 1/10 volume; if your audio is playing at 1/10 volume to begin with, that means we’ll only hear 1/100 the original volume. That’s not audible in any practical sense.
On the other hand, if I move the AudioSource closer to my camera and set its volume back to 1, I can hear it as clear as crystal.
So, check and make sure that you have the audio, and then see what needs to change so that you can hear it. A common pitfall in these situations is to forget the attenuation over distance.
As a static function, also according to the maximum distance it applies the sound proportionally.
public static void PlaySound(AudioClip clip, Transform collision, Transform player, int DistanceSoundLimit)
{
float cameraDistance = Vector3.Distance(player.position, collision.position);
float normalizedValue = Mathf.InverseLerp(0, DistanceSoundLimit, cameraDistance);
float explosionDistanceVolumen = Mathf.Lerp(1f, 0, normalizedValue);
// First, calculate the direction to the spawn
Vector3 spawnDirection = collision.position - player.position;
// Then, normalize it into a unit vector
Vector3 unitSpawnDirection = spawnDirection.normalized;
Debug.Log("Camera distance: " + cameraDistance + " explosion sound volumen : " + explosionDistanceVolumen);
// Now, we can play the sound in the direction, but not position, of the spawn
AudioSource.PlayClipAtPoint(clip, player.position + unitSpawnDirection, explosionDistanceVolumen);
}