Kokujou
1
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?
rutter
2
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));