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

Question How to stop music after scene change

Discussion in 'Scripting' started by Loykymar, Oct 21, 2021.

  1. Loykymar

    Loykymar

    Joined:
    May 23, 2021
    Posts:
    7
    Hi everyone,

    I have the following problem. Im really new to unity and building a text based game with scene changes. I finally managed to get music playing without starting from the beginning when changing a scene. (DoNotDestroy script)

    But I want to destroy it after entering a specific scene (Music just for the Menu, other music for game) , and some sound affects in between.

    What i want is that the music is constantly playing until i want a different sound/music to play on switching the scene.

    I use following script:



    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class DoNotDestroy : MonoBehaviour
    {
    private void Awake()
    {
    GameObject[] musicObj = GameObject.FindGameObjectsWithTag("GameMusic");
    if( musicObj.Length > 1)
    {
    Destroy(this.gameObject);
    }
    DontDestroyOnLoad(this.gameObject);


    }
    }



    Thanks for your help