Hi everyone!
So I’m working on a small 2D game project, a bullet hell. I want to play a hit sound effect every time the character is hit by a bullet. Also, I want this sound effect to randomly vary its pitch everytime this happens, to add a bit of variability. For those functions I have the following code:
This class initializes the static AudioManager class.
public class GameAudioSource : MonoBehaviour
{
private void Awake()
{
if(!AudioManager.Initialized)
{
//initialize audio manager and persist audio source across the game
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
AudioSource musicSource = gameObject.AddComponent<AudioSource>();
AudioManager.Initialize(audioSource, musicSource);
DontDestroyOnLoad(gameObject);
}
else
{
//duplicate game object, so destroy
Destroy(gameObject);
}
}
}
This static class manages all audio and is called from other classes when required:
public static class AudioManager
{
static bool initialized = false;
static AudioSource audioSource;
static AudioSource musicSource;
static Dictionary<AudioClipName, AudioClip> audioclips = new Dictionary<AudioClipName, AudioClip>();
public static bool Initialized
{
get { return initialized; }
}
public static void Initialize(AudioSource source, AudioSource soundtrackSource)
{
initialized = true;
audioSource = source;
musicSource = soundtrackSource;
audioclips.Add(AudioClipName.Hit01, Resources.Load<AudioClip>("Sounds/Hit 01"));
audioclips.Add(AudioClipName.Hit02, Resources.Load<AudioClip>("Sounds/Hit 02"));
audioclips.Add(AudioClipName.RecoveringHealth, Resources.Load<AudioClip>("Sounds/RecoveringHealth"));
audioclips.Add(AudioClipName.FOX, Resources.Load<AudioClip>("Sounds/Music/FOX"));
}
public static void Play(AudioClipName name)
{
audioSource.pitch = 1f;
audioSource.PlayOneShot(audioclips[name]);
}
public static void PlayMusic(AudioClipName name)
{
musicSource.pitch = 1f;
musicSource.volume = 0.75f;
musicSource.PlayOneShot(audioclips[name]);
}
public static void PlayWithRandomPitch(AudioClipName name)
{
audioSource.pitch = 1f;
AudioClip clip = audioclips[name];
float pitchNumber = Random.Range(0.75f, 1.5f);
audioSource.pitch = pitchNumber;
audioSource.PlayOneShot(audioclips[name]);
}
public static void PlayWithCustomPitch(AudioClipName name, float pitchNumber)
{
audioSource.pitch = 1f;
audioSource.pitch = pitchNumber;
audioSource.PlayOneShot(audioclips[name]);
}
}
My problem is this: when the game is playing a soundtrack and the character is hit by a bullet, the variation in pitch affects the soundtrack too, not only the “hit” sound effect. As it can be seen in the code, I tried using two different AudioSource components, one for sound effects and another for the soundtrack, but the problem persists. I’m not an expert at all on coding nor sound editing, so maybe I made a mistake I’m not catching.
Any ideas? Thanks in advance : )