game development

My Unity C# Code in how to loop a song

So if you have an intro part of the song and a looped part of the song for your Unity project (such as free songs from Wingless Seraph) (as 2 songs), I have written code in how to make them work (first play the intro then play the looped part indefinitely.

Here is the code:

  1.   public AudioSource[] musicSources;
  2.     private bool stop = false;
  3.     void Start()
  4.     {
  5.         musicSources[1].Stop(); //So it won’t automatically start
  6.     }
  7.     void Update()
  8.     {
  9.         if (!musicSources[0].isPlaying && !stop)
  10.         {
  11.             Debug.Log(“Stopped intro music and started the loop”);
  12.             musicSources[0].Stop();
  13.             musicSources[1].Play();
  14.             stop = true;
  15.         }
  16.     }

Have 2 Audio Source components. Set one for the intro song and one for the loop song. Set the loop check-mark true of the Audio Source of the loop. Then in the script, put the intro song into first field asking for the Audio Source, and the loop into the second one.
Set the first Music Time to however long the intro song lasts, in seconds as a decimal.

Also Read: WHY I CHOSE TO CANCEL GELOMANCER AFTER DEVELOPING IT FOR 4 YEARS

One Reply to “My Unity C# Code in how to loop a song

Leave a Reply

Your email address will not be published. Required fields are marked *