Script to carry on music to another scene not working now?

Hey,

I have a script which allows the same soundtrack to carry onto a new scene without resetting.

The idea is to attach an audiotrack to an empty gameobject tagged AppMusic and not to destroy it on load except the 2nd or (1) array meaning index 0 should just always remain active as index 1 is destroyed.

I initially built the game and it worked but today I opened my Unity project and when I tried to run the application on the editor I received an error stating:

IndexOutOfRangeException: Array index is out of range.
Music.Start () (at Assets/Script/Music.cs:19)

Here is the code:

using UnityEngine;
using System.Collections;

public class Music : MonoBehaviour
{

    private GameObject[] music;

    // Update is called once per frame
    void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
    }

    void Start()
    {
    
        music = GameObject.FindGameObjectsWithTag("AppMusic");
        Destroy(music[1]);

    }

}

I’m not sure what could of happen for the script to fail now. I didn’t change anything from what I recall.

Index out of range. So music[1] doesn’t exist.
Which means you don’t have enough tagged items to make your array that big.
You should add an if check to see if you even have > 1 items in your array before you try to destroy the second music object.

1 Like

Hey thank you very much. I kind of used your approach and solved it

if (music.Length > 1)
        {
           
            Destroy(this.gameObject);
        }

Thank you very much again!