Search Unity

Preventing music from overlapping while keeping other audio files enabled

Discussion in 'Scripting' started by danmct1995, May 5, 2020.

  1. danmct1995

    danmct1995

    Joined:
    Apr 21, 2020
    Posts:
    70
    I am trying to get my music to play and to prevent the music from stacking over each other on the next scene, I created a destroy & don't destroy method. The problem I am running into is when I start on a scene and an object with an audiofile is noticed by my script. The causes the script to immediately delete the music object. How would I go about either only selecting the music files length or find another solution around this?

    Code (CSharp):
    1.     private void Awake()
    2.     {
    3.         int MusicPlayingCount = FindObjectsOfType<AudioSource>().Length;
    4.         if (MusicPlayingCount > 1)
    5.         {
    6.             Destroy(gameObject);
    7.         }
    8.         else
    9.         {
    10.             DontDestroyOnLoad(gameObject);
    11.         }
    12.     }
     
    dinnerparty likes this.
  2. danmct1995

    danmct1995

    Joined:
    Apr 21, 2020
    Posts:
    70
  3. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    One thing I like doing with stuff like that is having an "into" scene where all my persistent managers/masters live.
    this is the first scene you load and never load it again.

    I'm not entirely clear on your problem tho, you can just tag them with either the unity game object tag or something you put on a component attached to the audio object and check that.

    You can also store a dictionary or whatever to tell you what is playing what.
     
  4. danmct1995

    danmct1995

    Joined:
    Apr 21, 2020
    Posts:
    70
    So if I have the music on the initial scene, I wouldn't need it on any others? I was told I needed multiple music files for each scene to prevent the music from stopping
     
  5. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536