Unity's default audio capabilities have never been a particular strong point. Some much needed functionality has been added over its lifespan, like audio mixers, sends, and insert effects, but it's still extremely limited compared to the feature sets found in widely used audio middleware and even other game engines.
Esla, consider Unity's game loop as this: 1. For each script (sequentially), run its Update method. Update physics (apply velocity to each object's position, etc.) 3. Your method prevents Unity from moving on to step 2, so x can never change. Apparently Unity docs are not using while statement in that example. Performance is a big issue with coroutines, specially when they contain infinite loop. Here is a video which explains it better. – Umair M Dec 12 '16 at 14:18.
In this post, I'm going to talk about 3 different potential approaches of gradually increasing complexity for looping music with native Unity audio. Hopefully, there will be something useful here for a variety of experience levels.
First we'll cover use Unity's default loop functionality. Second, we'll use a bit of audio editing and AudioClip PlayScheduled() to create a seamless loop. Lastly, we'll calculate a loop point given the beats per minute (BPM), beats per measure (Time Signature), and the total number of measures in the track and create a simple custom looping system, again using PlayScheduled().
Before starting, it should be noted the mp3 format is ill-suited for this application for technical reasons beyond the scope of this post and should be avoided. Ogg and Wav are good options that handle seamless looping well in Unity.
1. Default Loop
This is the simplest option, requiring no scripting at all, but it's also the most limited. For music that with no reverb or tail to speak of or music that doesn't need to restart exactly on measure, this can be serviceable. A quick fade at the end of the last bar can work for less ideal music tracks, but it will result in an obvious and unnatural loop point.
Create a new object in your scene, or use one that already exists. Whatever is appropriate.
Add an AudioSource component to it and set the AudioClip to your music file, either from the menu to the right of the field or by dragging and dropping it from the project browser.
Make sure that 'Play On Awake' and 'Loop' are enabled. Your music will play when you start the scene and loop at the end of the audio file.
2. Manual Tail/Release Overlap
This method requires some work outside of Unity with an audio editor or Digital Audio Workstation (DAW). Here we'll still use Unity's default looping functionality, after playing and introductory variation of the looped track.
Before doing anything in Unity you need two separate versions of the music track in question, one with the tail cut at the exact end time of the last bar/measure, and another with that tail transposed to the beginning of the track, so that it overlaps with the start.
Ensure that the start and end of these tracks are at a zero crossing, to avoid any discontinuities (audible pops) during playback. This can be accomplished with extremely short fades at the start and end points. This second track will transition seamlessly from the introductory track and loop seamlessly as well.
Add an AudioSource to an object as in the previous section and set the second edit of the track (with the tail overlapped with the start) as the default AudioClip. 'Play on Start' should NOT be enabled.
This is where a bit of scripting is required. Create a C# script and add it to the same game object as your AudioSource.
Open it in your IDE of choice. This will only require a few lines of code. First, declare two public variables: an AudioSource and an AudioClip
Save this and switch back to the Unity editor. There will be two new fields for the C# Script component in the Inspector: 'Music Source' and 'Music Start.'
Click and drag the AudioSource you added to your game object earlier into the 'Music Source' field on your script. Do the same with 'Music Start,' using the intro edit of the clip (without a tail at the start or end).
This is where the code that makes noise comes in.
When the scene Starts, the first clip will play once and the second clip will be scheduled to play as soon as the first has ended. This start time is determined simply by adding the length in seconds of the first clip to dspTime (the current time of the audio system in seconds, based on the actual number of samples the audio system processes).
From that point, the track will loop normally with Unity's default loop functionality.
3. Calculating the Loop Point and Looping Manually
The last approach requires more scripting work, and some extra information about the music itself, but does not require any specific editing of the audio file. We'll be creating a simple custom looping solution using two AudioSources and AudioSource.PlayScheduled() that calculates the end of the last bar or measure based on some data entered in the Inspector and uses that to determine the loop interval.
Add two AudioSources to your game object and set the default AudioClip for both to the music track you're going to loop. This will allow each repeat to overlap with the tail of the previous one as it plays out.
Add a new script to your game object and open it on your IDE. First, we need some public variables that we can set in the inspector: an array of AudioSources and three integer values which correlate to simple properties of the music composition itself.
In the inspector, set the Size of the Music Sources array to 2 and drag the two AudioSources you've created to the Element 0 and Element 1 fields.
Then enter a few music properties. Music BPM is the tempo of the music track in Beats Per Minute (BPM). Time Signature is the number of beats per bar/measure. and Bars Length is the number of bars/measures in the track. You need to know these values for this calculation to work.
Next, we need some private variables for some values we will be calculating in the script itself.
The loopPoint values will be used to store the loop interval once it has been calculated. Time will be the value of dspTime at the start of the scene and be incremented by loopPointSeconds for each PlayScheduled() time. And nextSource will be used to keep track of which AudioSource needs to be be scheduled next.
Now, in the Start() method we need the script to calculate the loop interval, play the first AudioSource, and initialize the time and nextSource values.
The custom loop functionality itself is defined in the Update() method, which is called every frame.
First, we check if the nextSource is still playing. Then, if it is NOT:
- Increment the time by the loop interval (loopPointSeconds).
- Schedule the nextSource AudioSource to play at that time.
- Toggle the value of nextSource (from 1 to 0 or from 0 to 1), so the script will check and schedule the other audio source.
And that's it. The music track should begin playing at the start of the scene and continue to repeat at the loop point until the object is destroyed.
Here, you will learn how to execute a statement or code block multiple times using the for loop, structure of the for loop, nested for loops, and how to exit from the for loop.
The for
keyword indicates a loop in C#. The for
loop executes a block of statements repeatedly until the specified condition returns false.
The for
loop contains the following three optional sections, separated by a semicolon:
Initializer: The initializer section is used to initialize a variable that will be local to a for loop and cannot be accessed outside loop. It can also be zero or more assignment statements, method call, increment, or decrement expression e.g., ++i or i++, and await expression.
Condition: The condition is a boolean expression that will return either true or false. If an expression evaluates to true, then it will execute the loop again; otherwise, the loop is exited.

Iterator: The iterator defines the incremental or decremental of the loop variable.
The following for loop executes a code block 10 times.
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
In the above example, int i = 0
is an initializer where we define an int variable i
and initialize it with 0. The second section is the condition expression i < 10
, if this condition returns true
then it will execute a code block. After executing the code block, it will go to the third section, iterator. The i++
is an incremental statement that increases the value of a loop variable i
by 1. Now, it will check the conditional expression again and repeat the same thing until conditional expression returns false
.The below figure illustrates the execution steps of the for
loop.
The below figure illustrates the execution steps of the for
loop.
If a code block only contains a single statement, then you don't need to wrap it inside curly brackets { }
, as shown below.
An Initializer, condition, and iterator sections are optional. You can initialize a variable before for
loop, and condition and iterator can be defined inside a code block, as shown below.

Nested For Loop Unity
Value of i: 0Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
Since all three sections are optional in the for
loop, be careful in defining a condition and iterator. Otherwise, it will be an infinite loop that will never end the loop.
The control variable for the for loop can be of any numeric data type, such as double, decimal, etc.
Value of i: 1.02
Value of i: 1.03
Value of i: 1.04
Value of i: 1.05
Value of i: 1.06
Value of i: 1.07
Value of i: 1.08
Value of i: 1.09

The steps part in a for loop can either increase or decrease the value of a variable.
Value of i: 9
Value of i: 8
Value of i: 7
Value of i: 6
Value of i: 5
Value of i: 4
Value of i: 3
Value of i: 2
Value of i: 1
Exit the for Loop
You can also exit from a for loop by using the break
keyword.
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Multiple Expressions

A for
loop can also include multiple initializer and iterator statements separated by comma, as shown below.
Value of i: 1, J: 1
Value of i: 2, J: 2
A for
loop can also contain statements as an initializer and iterator.
Iterator: i=1, j=4
Iterator: i=2, j=3
Iterator: i=3, j=2
Nested for Loop
For Loop List Unity
C# allows a for loop inside another for loop.
Unity Foreach Loop
Value of i: 0, J: 0Value of i: 0, J: 1
Value of i: 0, J: 2
Value of i: 0, J: 3
Value of i: 1, J: 1
Value of i: 1, J: 2
Value of i: 1, J: 3
