Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by alex963 · Apr 08, 2019 at 06:19 AM · audioarray list

Using arrays to play music with level loading doesn't seem to work.

Hi guys, this is my first post here. I have experience with GameMaker code and I am very new to C#.

My problem is as follows, I have a small game, and I want to be able to play music throughout it, but I have different stages with different levels, and I want the music to change every 3 scenes, as well as having the main menu music and potentially a game over one as well.

What I have done already, is I used arrays to list out the soundtrack, but I forgot how to increase the array.

Then I made an object that cant be destroyed, so I had one piece of music running throughout the game.

I experimented with DoNotDestroyOnLoad and found I had one continuous song.

Then I remembered how to make an array change, so I included in the code to the un-destroy-able object, and now it works, but it will not play the next song, but it will play the song on the main menu if I go in and out of it. Can someone please tell me what I am doing wrong or suggest a simpler version of my methods, or any better methods, my end goal is to have if statements testing what level I am currently in to change the soundtrack, at the moment it is just going scene to scene, the foundation is there.

The code is currently linked between the SceneLoader (Here) and the MusicManager (Below)

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.SceneManagement;
 using System;
 
 public class SceneLoader : MonoBehaviour {
 
 
     //check if there any other of this type, and delete accordingly
 
 
     public void Start()
     {
      
     }
 
     public void LoadNextScene ()
     {
         int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
         SceneManager.LoadScene(currentSceneIndex + 1);
         FindObjectOfType<MusicManager>().NextSong();
 
     }
     public void LoadStartScene ()
     {
         SceneManager.LoadScene(0);
         FindObjectOfType<GameSession>().ResetGame();
         FindObjectOfType<MusicManager>().RestartSoundtrack();
     }
     public void LoadPlayScene()
     {
         SceneManager.LoadScene(1);
         FindObjectOfType<MusicManager>().NextSong();
     }
     public void ExitGame ()
     {
         Application.Quit();
     }
 }


.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.SceneManagement;
 
 public class MusicManager : MonoBehaviour
 {
     [SerializeField] AudioClip[] soundTrack;
     [SerializeField] int currentTrack = 0;
 
     AudioSource audioSource;
 
     void Start()
     {
         AudioClip clip = soundTrack[currentTrack];
         AudioSource.PlayClipAtPoint(clip, Camera.main.transform.position);
     }
     
     private static MusicManager instance = null;
     public static MusicManager Instance
     {
         get { return instance; }
     }
     void Awake()
     {
         int gameStatusCount = FindObjectsOfType<GameSession>().Length;
         if (gameStatusCount > 1)
         {
             gameObject.SetActive(false);
             Destroy(gameObject);
         }
         else
         {
             DontDestroyOnLoad(gameObject);
         }
     }
     public void NextSong()
     {
         currentTrack++;
         AudioClip clip = soundTrack[currentTrack];
         AudioSource.PlayClipAtPoint(clip, Camera.main.transform.position);
     }
     public void RestartSoundtrack()
     {
         currentTrack = 0;
         AudioClip clip = soundTrack[currentTrack];
         AudioSource.PlayClipAtPoint(clip, Camera.main.transform.position);
     }
 
 }
 

please Note that currentTrack is only serialized so i can check if it is going up, and yes it is going up and working.

Alex.

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image alex963 · Apr 08, 2019 at 12:10 AM 0
Share

Sorted it, here is my fix.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.Scene$$anonymous$$anagement;
 
 public class $$anonymous$$usic$$anonymous$$anager : $$anonymous$$onoBehaviour
 {
     [SerializeField] public AudioClip [] soundTrack;
     [SerializeField] int currentTrack = 0;
 
     public AudioSource audioSource;
 
     void Start()
     {
         currentTrack = 0;
         audioSource.clip = soundTrack[currentTrack];
         audioSource.Play();
     }
 
     private static $$anonymous$$usic$$anonymous$$anager instance = null;
     public static $$anonymous$$usic$$anonymous$$anager Instance
     {
         get { return instance; }
     }
     void Awake()
     {
 
         int gameStatusCount = FindObjectsOfType<$$anonymous$$usic$$anonymous$$anager>().Length;
         if (gameStatusCount > 1)
         {
             gameObject.SetActive(false);
             Destroy(gameObject);
         }
         else
         {
             DontDestroyOnLoad(gameObject);
         }
     }
     public void NextSong()
     {
         currentTrack++;
         audioSource.clip = soundTrack[currentTrack];
    
         audioSource.Play();
     }
     public void RestartSoundtrack()
     {
         currentTrack = 0;
         audioSource.clip = soundTrack[currentTrack];
         currentTrack = 0;
         audioSource.Play();
     }
 
 
 }

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Rickywild · Apr 08, 2019 at 11:58 PM

Here's a magical relic.

     using UnityEngine;
     using System.Collections;
     
     public class AudioManager : MonoBehaviour
 {
 
     public static AudioManager instance = null;
 
     public static float masterVol, sfxVol, musicVol, masMax, sfxMax, musMax;
 
     //AudioData struct defined at bottom of class.
 
     //AUDIO FOR LEVELS
     public static AudioData lvl01Aud, lvl02Aud; //ect
 
     //AUDIO FOR PLAYER
     public static AudioData jumpAud, dodgeAud, sprintAud;//ect;
 
     //AUDIO FOR ENEMIES
     public static AudioData enemyJumpAud, enemyAtkAud; //ect
 
     //AUDIO FOR ITEMS
     public static AudioData goldAud, keyAud;
 
 
 
 
 
     void Start()
     {
 
     }
 
     void Awake()
     {
         //Create one instance of object and make persistant.
         if (instance == null)
         {
             instance = this;
 
             masMax = 1.0f;
             sfxMax = 1.0f;
             musMax = 1.0f;
 
             masterVol = 1.0f;
             sfxVol = 0.7f;
             musicVol = 0.5f;
 
 
             Initialize_LevelAud();
             Initialize_PlayerAud();
             Initialize_EnemyAud();
 
         }
         else if (instance != this)
         {
             Destroy(gameObject);
         }
         DontDestroyOnLoad(gameObject);
 
 
     }
 
 
     void Update()
     {
         PlaySceneAudio();
     }
 
 
     private void LevelOneLogic()
     {
         if (!GameManager.pause)
         {
             lvl01Aud.UnPause();
             lvl01Aud.Enable(true, musicVol);
             lvl01Aud.SetVol(musicVol);
 
         }
         else
         {
             lvl01Aud.Pause();
         }
     }
 
     private void PlaySceneAudio()
     {
         switch(GameManager.currentSceen)
         {
             case 1: //LEVEL 01
 
                 break;
             case 2: //LEVEL 02
 
                 break;
         }
 
     }
 
     public static void RunPlayerSFX(int i)
     {
         switch (i)
         {
             case 1:
                 jumpAud.PlaySFX(false, sfxVol / 6);
                 break;
             case 2:
 
                 break;
             case 3:
 
                 break;
 
         }
     }
 
     public static void RunEnemySFX(int i)
     {
         switch (i)
         {
             case 1:
                 enemyJumpAud.PlaySFX(true, sfxVol / 8);
                 break;
             case 2:
 
                 break;
 
 
         }
     }
 
     public static void RunItemSFX(int i)
     {
         switch (i)
         {
             case 1:
                 
                 break;
             case 2:
 
                 break;
 
         }
     }
 
 
     private void Initialize_LevelAud()
     {
         lvl01Aud = new AudioData("lvl01", musicVol, false, true); //resources folder .wav
         lvl02Aud = new AudioData("lvl02", musicVol, false, true); //resources folder .wav
 
         //Assign all audio under this manager within editor hiearchy.
         lvl01Aud.obj.transform.parent = this.transform;
         lvl02Aud.obj.transform.parent = this.transform;
     }
 
 
     private void Initialize_PlayerAud()
     {
         jumpAud = new AudioData("jump", musicVol, false, true); //resources folder .wav
 
         //Assign all audio under this manager within editor hiearchy.
         jumpAud.obj.transform.parent = this.transform;
 
     }
 
     private void Initialize_EnemyAud()
     {
         enemyJumpAud = new AudioData("badguyjump", musicVol, false, true); //resources folder .wav
 
         //Assign all audio under this manager within editor hiearchy.
         enemyJumpAud.obj.transform.parent = this.transform;
     }
 
 
     public class AudioData
     {
         public float vol;
         public GameObject obj;
         public AudioSource src;
         public AudioClip clip;
 
         private float timeStamp, waitTime;
         public bool timeStamped, fadeInFin;
         private bool paused;
 
         public AudioData(string fileName, float volume, bool loop, bool music)
         {
             this.obj = new GameObject();
             this.src = (AudioSource)this.obj.AddComponent(typeof(AudioSource));
             this.clip = (AudioClip)Resources.Load(fileName, typeof(AudioClip));
 
             this.src.clip = this.clip;
             this.src.loop = loop;
             this.vol = this.src.volume = volume;
             //this.src.pitch = 1.000f;
 
             timeStamp = 0f;
             waitTime = 8f; //8 secs
             timeStamped = false;
             fadeInFin = false;
             paused = false;
 
             if (music)
                 obj.name = fileName + " Music";
             else
                 obj.name = fileName + " Sound";
 
             DontDestroyOnLoad(obj.gameObject); //this works. src.gameObject
         }
 
         public void AddToVol(float v)
         {
             this.src.volume += v;
         }
 
         public void MinToVol(float v)
         {
             this.src.volume -= v;
         }
 
         //public float Vol
         //{
         //    get
         //    {
         //        return this.vol;
         //    }
         //    set
         //    {
         //        //if(this.vol <= SfxVol)
         //        this.vol = value;
         //    }
         //}
 
         public void SpeedUp(float pitchLvl)
         {
             if (this.src.pitch < pitchLvl)
             {
                 this.src.pitch += Time.deltaTime;
             }
             else
             {
                 if (this.src.pitch > pitchLvl)
                     this.src.pitch = pitchLvl;
                 else
                     return;
             }
         }
 
         public void SlowToHalt(float pitchLvl)
         {
             if (this.src.pitch > pitchLvl)
             {
                 this.src.pitch -= Time.deltaTime;
             }
             else
             {
                 if (this.src.pitch < 0f)
                     this.src.pitch = 0f;
                 else
                     return;
             }
         }
 
         public void ReturnToPlay()
         {
             if (this.src.pitch < 1f)
             {
                 this.src.pitch += Time.deltaTime;
             }
             else
             {
                 if (this.src.pitch > 1f)
                     this.src.pitch = 1f;
                 else
                     return;
             }
 
         }
 
         public void SetPitch(float p)
         {
             if (this.src.pitch != p)
                 this.src.pitch = p;
             else
                 return;
         }
 
         public void SetVol(float v)
         {
             if (this.src.volume != v)
                 this.src.volume = v;
             else
                 return; //Don't needlessly apply same volume values.
         }
 
         public float GetVol()
         {
             return this.src.volume;
         }
 
         public void Play(bool safePlay)
         {
             if (safePlay)
             {
                 if (!this.src.isPlaying)
                     this.src.Play();
             }
             else
                 this.src.Play();
 
         }
 
         public void PlaySFX(bool safePlay, float v)
         {
             if (this.src.volume != v)
                 this.src.volume = v;
 
             if (safePlay)
             {
                 if (!this.src.isPlaying)
                     this.src.Play();
                 else
                     return;
             }
             else
                 this.src.Play();
 
         }
 
         public void UnPause()
         {
             if (paused)
             {
                 paused = false;
                 this.src.UnPause();
             }
         }
 
         public void Pause()
         {
             if (!paused)
             {
                 paused = true;
                 this.src.Pause();
             }
         }
 
         public void Stop()
         {
             if (this.src.isPlaying)
                 this.src.Stop();
         }
 
         public void FadeOut(float rate)
         {
 
             if (!timeStamped)
             {
                 timeStamp = Time.time;
                 fadeInFin = false;
                 timeStamped = true;
             }
 
             if (Time.time < timeStamp + waitTime)
             {
                 if (this.src.volume >= 0)
                 {
                     this.src.volume -= rate;
                     if (timeStamped)
                         timeStamped = false;
 
                     //return false; //Audio not faded out yet.
                 }
                 else
                 {
                     this.src.Stop();
                     timeStamp = 0f;
                     //return true; //Audio successfully faded out completely, volume wise.
                 }
 
             }
 
         }
 
         public void FadeIn(float rate, float limit)
         {
             if (!fadeInFin)
             {
                 if (!this.src.isPlaying)
                     this.src.Play();
 
                 if (!timeStamped)
                 {
                     timeStamp = Time.time;
                     this.src.volume = 0f;
                     timeStamped = true;
                 }
 
                 if (Time.time < timeStamp + waitTime)
                 {
                     if (this.src.volume <= limit)
                     {
                         this.src.volume += rate;
 
 
                         //return false; //Audio not faded in yet.
                     }
                     else
                     {
                         //this.src.Stop();
                         timeStamp = 0f;
                         if (timeStamped)
                             timeStamped = false;
                         fadeInFin = true;
                         //return true; //Audio successfully faded in completely, volume wise.
                     }
 
                 }
             }
 
         }
 
         public void Disable()
         {
             if (this.obj.activeSelf)
             {
                 this.Stop();//was at bottom
 
                 this.obj.SetActive(false);
                 this.fadeInFin = false;
                 this.src.volume = 0f;
 
                 this.timeStamped = false;
             }
 
 
         }
 
         public void Enable(bool volSet, float volume)
         {
             if (!this.obj.activeSelf)
             {
                 this.obj.SetActive(true);
                 this.fadeInFin = false;
                 this.timeStamped = false;
                 if (volSet)
                     this.src.volume = volume;
 
                 this.Play(true);
             }
 
 
 
         }
 
 
     }
 
 
 }
 
 
 



Farewell and good luck.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

133 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Spatialised audio choppy when used with timelines 0 Answers

Play Audio on Collision or Trigger Enter 4 Answers

How can we change default playback device in unity? 2 Answers

Audio Question 2 Answers

Array in JS NOT Working with Components?! 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges