- Home /
Audio playing not in right time when calling from script
Hi There. I think the Unity is trolling me:
I have several scenes that goes one after another. To control this I created the simple button for taping:
public void SceneControl()
{
sceneNavigator += 1;
}
I tap the button and go from scene 0 to scene 1. Tap next and go from 1 to 2... The problem is when I want to play sound in scene 1:
if (sceneNavigator == 1)
{
soundToPlay1.Play();
}
It's not playing. It plays only when I tap second time. When the scene 1 is over. Not matter how long I wait to tap second time. It always play on next scene. By the way, it's empty:
if (sceneNavigator == 2)
{
}
I dont know what I doing wrong. Please, Help me people!
Are you sure that you have an audioSource which can play the sound on each scene ?
And it's not like this that it should works, look the API https://docs.unity3d.com/ScriptReference/AudioSource.Play.html
You said soundToPlay.Play() ins$$anonymous$$d of AudioSource.Play(soundToPlay);
you usually call Play on an instance, not the class
the scripts are not even telling when and where the actual scene is loaded. my guess is that audio play is called prior to loading a scene. this means the audio source that should play is destroyed. and since there is no second scene to load the one from scene one stays and plays. do play the scene source on start or something, from within the scene that is loaded.
Answer by unity_5a5EJgiiHc07NA · Jul 12, 2018 at 07:43 PM
I don't know why it's working but I change soundToPlay.Play()
to soundToPlay.PlayOneShot()
. Now everything going well. P.S.: If you hear some noise effects just do like here: https://answers.unity.com/questions/451895/distorted-audio-using-playoneshot.html Or add a trigger:
if (!isPlayed)
{
soundToPlay.PlayOneShot();
isPlayed = true;
}
Thanks everybody for answers.
it's working because PlayOneShot creates an AudioSource on the fly to play the sound, which is unaffected by scene loading. it's basically bypassing the problem.
Your answer
Follow this Question
Related Questions
AudioSource playing with delay for 1 step 0 Answers
Audio Clip Playing every frame 2 Answers
Fade, Then Stop all other audiosources attached to gameobject? 1 Answer
Multiple gapless sound loops from one AudioSource (C#) 2 Answers
How to play "audiosource" component in a prefab from script? 0 Answers