Loading MP3's into an Audio Array and assigning them to members of a GameObject Array

StackOverflow https://stackoverflow.com/questions/21872205

  •  13-10-2022
  •  | 
  •  

Domanda

I'm trying to load an array of MP3 files from the Resources folder, and then assign each MP3 file to the Audio Clip value of a GameObject.

This list of GameObjects (referred to as "Notes") is sorted, and the MP3 files are already sorted manually (their names are in numerical order).

Below is my attempt, I've removed the sorting method SortNotes() to save space (it works perfectly fine, isn't the issue).

// An array of Notes
public GameObject[] NotesArray;

AudioClip[] pickupMP3s;

// Use this for initialization
void Start () {
    // Grab and sort array of Notes
    NotesArray = GameObject.FindGameObjectsWithTag("Note");
    SortNotes();

    // Grab a list of pick-up mp3 files
    pickupMP3s = Resources.LoadAll("..\\Level 4\\Level 4 Pickup Tracks") as AudioClip[];
}

// Assign each mp3 file to a Note
void AssignNotes(){
    for (int i = 0; i < NotesArray.Length; i++){
        foreach (GameObject note in NotesArray){
            try{
                note.audio.clip = pickupMP3s[i];
                Debug.Log(pickupMP3s[i]);
                Debug.Log(note.audio.clip.name);
            }catch(Exception e){
                Debug.Log(e.ToString());
            }
        }
    }   
}

I get tons of NullReferenceException: Object reference not set to an instance of an object errors. They seem to stem from this line: note.audio.clip = pickupMP3s[i]; but I can't figure out what.

The objects already have Audio Sources attached.

È stato utile?

Soluzione 2

Resolved here.

The issue was the type cast of the pickupMP3s assignment. It should have been:

pickupMP3s = Resources.LoadAll<AudioClip>("Level4/Level4_Pickup_Tracks"); 

Additionally the troublesome line should have been

NotesArray[i].audio.clip = pickupMP3s[i]; 

instead of

note.audio.clip - pickupMP3s[i];

Altri suggerimenti

Are the lengths of NotesArray and pickupMP3s the same? I would do a break point at your for loop and just see when the exception occurs. When it happens, check to see if you're out of the index range on pickupMP3s array.

Another error could be the fact that your note.audio object is not instantiated, so when you try to set its clip property, it throws the error. Going through with a debugger by setting a break point would let you know which object is null. I'm not sure from the code above, but I would asume you have a note object that has an audio object as one of its properties, that has a clip property. You didn't show any of the code that shows if note.audio is being instantiated (or even note), so it's hard to tell. Make sure that you're instantiating all of them.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top