Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Audio looping not working after a coroutine

Discussion in 'Audio & Video' started by DrainKare, Jan 25, 2021.

  1. DrainKare

    DrainKare

    Joined:
    Dec 16, 2020
    Posts:
    2
    Hi, I'm new to unity, I have a problem that is driving me crazy, I made an audio transition using a coroutine (Just a simple fade in), but then the audio looping is not working.
    The whole process is the next one: I have an animation event that calls a function in the gameObject's script that is being animated, the only purpose of this function is to call another function in my SoundManager script.

    Code (CSharp):
    1.  public void callMusic ()
    2.     {
    3.         soundManger.PlayBackgroundMusic();
    4.     }
    This is the function that the animation event calls

    This function calls the coroutine I did set up for the audio to fade in, and just plays the sound, but when the audio finishes doesn't loop.

    Code (CSharp):
    1. public class SoundManager : MonoBehaviour
    2. {
    3.     AudioSource audioSource;
    4.  
    5.     void Awake()
    6.     {
    7.         audioSource = GetComponent<AudioSource>();
    8.     }
    9.    
    10.     // Plays the music
    11.     public void PlayBackgroundMusic()
    12.     {
    13.         audioSource.PlayOneShot(audioSource.clip);
    14.         StartCoroutine("FadeIn");
    15.     }
    16.  
    17.  
    18.     // Fade in "Animation"
    19.     IEnumerator FadeIn ()
    20.     {
    21.         while (audioSource.volume < 1.0f)
    22.         {
    23.             audioSource.volume += Time.deltaTime / 6.0f;
    24.             yield return null;
    25.         }
    26.              
    27.     }
    28. }
    I have the loop checkbox checked in the AudioSource component, and also tried looping from inside the script, and none of this worked.

    can someone please tell me what am I doing wrong? :(
     
  2. JLF

    JLF

    Joined:
    Feb 25, 2013
    Posts:
    137
    Hi. Looks like you’re using PlayOneShot which doesn’t loop. Try using Play instead.
     
    DrainKare likes this.
  3. DrainKare

    DrainKare

    Joined:
    Dec 16, 2020
    Posts:
    2
    That was exactly it, thank you so much!