I’m completely new to unity and blender but for my school project i wanted to make objects react to sounds.
Can anybody point me into a direction on what/which codes i need or a good tutorial for beginners? Perhaps someone made something similar maybe…?
To get an idea what i want:
I made a cave in blender and I want creatures to light up and fly towards the end of the cave whenever there is a loud noise. And the longer the sound continue, the more creatures are showing up. (By noise and sounds i mean the surroundings, so a camera has to record the sound of course)
You don’t want to listen for sounds specifically, because you’d have to A) figure out how to get the audio stream, B) figure out how to have multiple AudioListeners in a scene, C) do a lot of heavy processing on the audio, per enemy. Fortunately, you can simplify it a ton, because you only need to know that a loud thing played at X point at Y volume, and that information is easy.
Everything that makes a sound that can be heard by the enemies should have a script on it (let’s call it NoiseMaker), and you call a function on this script every time the sound is played. Maybe you want to go so far as to play all sounds through this script in the first place. On the enemies, have a NoiseListener script, and a static function can figure out which of them can hear.
public class NoiseMaker : MonoBehaviour {
public void MakeNoise(float noiseRange) {
NoiseListener.Listen(transform.position, noiseRange);
}
//elsewhere
GetComponent<NoiseMaker>().MakeNoise(5f);
//NoiseListener.cs
public void NoiseListener : MonoBehaviour {
//this part will maintain a list of all noise listeners for us to use in the Listen function
private static List<NoiseListener> allListeners = new List<NoiseListener>();
void OnEnable() {
allListeners.Add(this);
}
void OnDisable() {
allListeners.Remove(this);
}
//this event will trigger when it hears a sound; you can assign things in the inspector.
public UnityEvent OnHearSound;
public static void Listen(Vector3 noisePos, float noiseRange) {
foreach (var listener in allListeners) {
if ( (listener.transform.position - noisePos).magnitude < noiseRange) {
listener.OnHearSound.Invoke();
}
}
}
I haven’t tested any of this so it may not be 100% right, but this is pretty close to what you want