Hello, I am new to Unity and I’m working on my first game.
An unexpected thing happened. I closed Unity with everything working fine, and the next time I opened it there was a strange behavior from the audio.
I have an attack method, for when the character attacks, in which I have this:
if (playerBody.GetComponent<ApplyControls>().isAttacking)
{
anim.SetBool("IsAttacking", true); // Animator component that plays the attack animation.
audioPlayer.pitch = Random.Range(0.8f, 1.1f);
audioPlayer.volume = Random.Range(0.8f, 1f);
audioPlayer.Play(); // The Audio Source component.
}
Pretty simple. If the player is attacking, play the relevant animation, and sound effect. The thing is that while the animation plays on time, the sound effect has a terrible delay of more than a second, and aside from that I can hear some kind of noise before the sound effect plays.
I’m surprised because sound was working perfectly since some hours ago, and I haven’t touched anything related to audio for about a week. And all that time the sound effect played at the right time and without noises.
Neither I changed a sound card driver or anything like that. What is happening and why ?
Just a guess, but it might make sense to cache a reference to ApplyControls instead of calling GetComponent every time (seems not to be the most resource friendly thing to do). Not sure about the audio artefacts you’re getting. There might be other stuff going on, hard to tell.
Yup, thanks for the tip, but right now it’s the sound problem that interests me. Lets make it first to work, and then we can optimize it.
Here is some more info: I removed the sound file from the project and reimported it, and I also removed the attached Sound Source and added a new one. Now the sound effect plays on Awake if the corresponding editor option is checked, and it sounds without noise. But after that, it doesn’t play at all! While on play mode, I noticed that its volume and pitch sliders do indeed change randomly (as I scripted it to do), but checking the mixer, it shows it has no signal on the corresponding channel. I even tried removing the mixer from the Output variable to see if it’s the mixer that has the problem, and still the sound effect just doesn’t play any more. Only once on Awake, if Play on Awake is checked.
I was hinting that that might be one thing that’s causing your problems :). And without more details it’s hard to tell where else there could be any problems :).
My guess is your sound effect is an mp3, which takes about 50 times as long to start playing. Normally that just causes a very slow frame, but it may be possible that it could go out of sync. Try a wav or ogg file instead.
Temporarily remove your pitch / volume code until you get it working properly without.
Also, make a new game object in case something got corrupted. Get rid of the old one.