Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Audio Changing Music During Gameplay Stops Music

Discussion in 'Audio & Video' started by Radicool, Aug 21, 2019.

  1. Radicool

    Radicool

    Joined:
    Aug 21, 2019
    Posts:
    2
    [Solved - see below post]

    Hi everyone,

    I'm very new to Unity and coding in general and am having trouble changing the music in my scene. I have an AudioSource and AudioListener component attached to my "Main Camera". I successfully made background music play and loop without any C# code by ticking "Play on Awake" and "Loop" in the AudioSource component.

    Now I want some victory music to play when my character reaches the end of the level. The code runs from my "MusicSystem" script which is also a component of my "Main Camera". When my player reaches the end of the level, I see the debug message "ChangeMusic executed", but the music just abruptly stops and the victory music does not play.

    Can anyone tell me why my code isn't changing the music?

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class MusicSystem : MonoBehaviour
    7. {
    8.  
    9.     // Below variables are for accessing and playing music
    10.     private AudioSource gameMusic;
    11.     private AudioClip endLevelClip;
    12.     private int position = 0;
    13.     private int sampleRate = 44100;
    14.     private int frequency = 440;
    15.  
    16.     // Start is called before the first frame update
    17.     void Start()
    18.     {
    19.  
    20.         gameMusic = gameObject.GetComponent<AudioSource>(); // Get the AudioSource of the camera
    21.         endLevelClip = AudioClip.Create("EndLevel", sampleRate * 2, 1, sampleRate, true); // Create a new audio clip
    22.  
    23.     }
    24.  
    25.     public void ChangeMusic()
    26.     {
    27.  
    28.         Debug.Log("ChangeMusic executed");
    29.         gameMusic.clip = endLevelClip; // Make the Audiosource use the new clip.
    30.         gameMusic.Play();
    31.  
    32.     }
    33. }
    34.  
     
    Last edited: Aug 23, 2019
  2. Radicool

    Radicool

    Joined:
    Aug 21, 2019
    Posts:
    2
    For anyone interested, I found a solution. I followed the below guide to learn how to change the music in a scene during gameplay. It involved changing my code a bit.