- Home /
Unity - Play AudioSource without delay
The Problem is: I'm playing some sort of animation... in general its the rotation of a text over a period of time using the Thread.Sleep() Function (C#) I want to Play a Sound while this Animation loads but when i play the audio source the sound starts playing when the animation already ended !! it's not a very long animation and it's not in the audio file. i checked it there is no delay in the file so it has to be in the code somewhere. what can i do to get rid of this delay?
Why are you using Thread.Sleep() ? Can't you create a Unity Animation to rotate the text.. then the audio should play ok?
I'm not quite sure how you're rotating with Thread.Sleep, but I'd guess putting the thread to sleep is delaying the audio source.
Try placing the Audio.play() right before the Thread.Sleep
of course thats what i ded !! i added the audio.play right before the Sleep function and i use the Sleep function for a delay because my "animation" is just ... set new rotation -> wait 20msec -> set another new rotation etc... thats basically it because i'm not used to unity i don't know any ways how to make it better ^-^ i don't know how to create a real animation
Answer by rutter · Sep 11, 2014 at 11:47 PM
You should almost never perform blocking operations on Unity's main thread. Doing so will freeze the entire engine while you wait.
It's better to use timers that update once per frame, such as coroutines.
For example, this coroutine:
IEnumerator Spin(Vector3 spin, float duration) {
Vector3 spinPerSecond = spin / duration;
for (float time = 0f; time <= duration; time += Time.deltaTime) {
transform.Rotate(spinPerSecond * Time.deltaTime); //spin a little bit
yield return null; //wait for next frame
}
}
//call this elsewhere:
Vector3 spinAxis = Vector3.up;
float spinDegrees = 360f;
float spinSeconds = 2f;
StartCoroutine(Spin(spinAxis * spinDegrees, spinSeconds));
lets see if i get this correct: float duration is the complete duration of the whole animation right? so it rotates as long as this duration is not fit? and Vector3 spin is the complete rotation ... the number of degrees it will rotate in the given duration... i'll try if this works better thank you !!
It worked perfectly thank you !! i can use this very good ... well the only Problem with your Rotate version was that it didn't stop in 360 degrees... the resulting text was a bit escrow. but the animation is very fast so it doesn't matter when i just but it from 0 to 100 in the original direction ^-^ thank you !! that helped me a lot
Your answer