NeedHelp: Attempting to make a script that would play AudioClips based on Scene Index Numbers using an Array
Hello,
I created a game object with a script attached to it. Its main purpose is to hande music clips throughout the game (not being destroyed on load). I managed to use create an array and use SceneManager.GetActiveScene().buildIndex for getting relevant scene numbers.
However, I am unable to come up with a working script that would use the scene number (that is correctly read from SceneManager.GetActiveScene().buildIndex) to point to an item attached to a relevant number in an array. In short, no music is being played neither on start of a scene 0 nor on any following scenes.
Here is what I got this far:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class MusicPlayerScript : MonoBehaviour {
public AudioClip[] MusicPerSceneArray;
private AudioSource audioSource;
private int MusicSceneNumber;
private void Awake()
{
DontDestroyOnLoad(gameObject);
MusicSceneNumber = SceneManager.GetActiveScene().buildIndex;
Debug.Log(MusicSceneNumber);
}
// Use this for initialization
void Start() {
audioSource = GetComponent<AudioSource> ();
}
void MusicPerScene()
{
AudioClip thisLevelMusic = MusicPerSceneArray[MusicSceneNumber];
if (thisLevelMusic)
{
audioSource.clip = thisLevelMusic;
audioSource.loop = true;
audioSource.Play();
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612130832im_/https://answers.unity.com/themes/thub/images/avi.jpg)