Need help with the music manager

I’ve the same script as the course but, when i run the game and the level loader move me from the splash screen to the start screen, my console says “Object reference not set an instance of an object” (line 19 of the option controller). when I go to the option scene and try to move the slider the console says the same thing but for the music manager (look at the photo).


my codes are:
music player

    > 1. using UnityEngine;
> 2.     using System.Collections;
> 3.         public class MusicPlayer : MonoBehaviour {
> 4.             static MusicPlayer instance = null;
> 5.             public AudioClip[] levelMusicIsChangeArray;
> 6.             private static AudioSource audioSource;
> 7.              void Awake()
> 8.             {
> 9.                 DontDestroyOnLoad(gameObject);
> 10.             }
> 11.              private void Start()
> 12.             {
> 13.                 audioSource = GetComponent<AudioSource>();
> 14.                 audioSource.volume = PlayerPrefsManager.GetMasterVolume(); 
> 15.             }
> 16.             private void OnLevelWasLoaded(int level)
> 17.             {
> 18.                 AudioClip thisLevelMusic = levelMusicIsChangeArray[level];
> 19.                 Debug.Log("Playing Clip on Level " + thisLevelMusic);
> 20.                 if (thisLevelMusic)
> 21.                 {
> 22.                     audioSource.clip = thisLevelMusic;
> 23.                     audioSource.loop = true;
> 24.                     audioSource.Play();
> 25.                 }
> 26.             }
> 27.             public void SetVolume(float volume)
> 28.             {
> 29.                 audioSource.volume = volume;
> 30.             }
> 31.         }

option controller

  1. >      using System.Collections;
2. >                 using System.Collections.Generic;
3. >                 using UnityEngine.UI;
4. >                 using UnityEngine;
5. >                 public class OptionController : MonoBehaviour {
6. >                     public Slider volumeSlider, difficultySlider;
7. >                     public LevelManager levelManager;
8. >                     private static MusicPlayer musicPlayer;
9. >                     // Use this for initialization
10. >                     void Start () {
11. >                         GameObject.FindObjectOfType<MusicPlayer>();
12. >                         volumeSlider.value = PlayerPrefsManager.GetMasterVolume();
13. >                         difficultySlider.value = PlayerPrefsManager.GetDifficulty();
14. >                 	}
15. >             	// Update is called once per frame
16. >             	void Update () {
17. >                     musicPlayer.SetVolume(volumeSlider.value);
18. >             	}
19. >                 public void SaveAndExit()
20. >                 {
21. >                     PlayerPrefsManager.SetMasterVolume(volumeSlider.value);
22. >                     PlayerPrefsManager.SetDifficulty(difficultySlider.value);
23. >                     levelManager.LoadLevel("Start Menu");
24. >                 }
25. >                 public void SetDefaults()
26. >                 {
27. >                     volumeSlider.value = 0.8f;
28. >                     difficultySlider.value = 2f;
29. >                 }
30. >             }

what should I do?
I have unity 5.6.3

Hi,

I don’t think those line numbers are corresponding very well with the code you have posted, possibly due to adding the line numbers.

Could you just copy/paste both scripts in, without the line number, but use the code formatting so that it’s a little more readable. Thanks :slight_smile:


See also;

option controller;

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine.UI;
    using UnityEngine;

    public class OptionController : MonoBehaviour {
        public Slider volumeSlider, difficultySlider;
        public LevelManager levelManager;
        private static MusicPlayer musicPlayer;
        // Use this for initialization
        void Start () {
            GameObject.FindObjectOfType<MusicPlayer>();
            volumeSlider.value = PlayerPrefsManager.GetMasterVolume();
            difficultySlider.value = PlayerPrefsManager.GetDifficulty();
    	}
    	
    	// Update is called once per frame
    	void Update () {
            musicPlayer.SetVolume(volumeSlider.value);//line 19
    	}
        public void SaveAndExit()
        {
            PlayerPrefsManager.SetMasterVolume(volumeSlider.value);
            PlayerPrefsManager.SetDifficulty(difficultySlider.value);
            levelManager.LoadLevel("Start Menu");
        }
        public void SetDefaults()
        {
            volumeSlider.value = 0.8f;
            difficultySlider.value = 2f;
        }
    }

music player ;

using UnityEngine;
using System.Collections;

public class MusicPlayer : MonoBehaviour {
    static MusicPlayer instance = null;
    public AudioClip[] levelMusicIsChangeArray;
    private static AudioSource audioSource;
     void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }
     private void Start()
    {
        audioSource = GetComponent<AudioSource>();
        audioSource.volume = PlayerPrefsManager.GetMasterVolume(); 
    }
    private void OnLevelWasLoaded(int level)
    {
        AudioClip thisLevelMusic = levelMusicIsChangeArray[level];
        Debug.Log("Playing Clip on Level " + thisLevelMusic);
        if (thisLevelMusic)
        {
            audioSource.clip = thisLevelMusic;
            audioSource.loop = true;
            audioSource.Play();
        }
    }
    public void SetVolume(float volume)
    {
        audioSource.volume = volume; //line 30
    }
}

Ok,

In OptionController you don’t initialise the musicPlayer variable in your Start method;

GameObject.FindObjectOfType<MusicPlayer>();

should be;

musicPlayer = GameObject.FindObjectOfType<MusicPlayer>();

This would account for both of the OptionController errors in the console, before looking any further I would suggest correcting that line and then running the game again, as it’s possible the four errors relate to the same issue.

thank you, it worked, but for only 2 problems :frowning:

You’re welcome, and great.

Ok, so two left to go…

For the next two errors, line 23 could be either the audioSource or the thisLevelMusic being null, I would guess probably the former, but we should check.

In your Start method, you have this line;

audioSource = GetComponent<AudioSource>();

Immediately after it, add this;

if(!audioSource)
{
    Debug.Log("I don't have an AudioSource");
}

Run the code and see if this message appears in the console.

The message doesn’t appear in the console. Maybe it’s because that music player code doesn’t work on unity 5.6

Presumably the GameObject in the scene is called Persistant Music and that is the one with the MusicPlayer script attached?

If that message doesn’t appear then, at least in the first instance you have an AudioSource (assuming the code is running). You could confirm this by replacing that if statement with this one;

if(audioSource)
{
    Debug.Log("I have an audio source");
}

Note, the only difference is the removal of the ! character.

I note that you also have the MusicPlayer instance set to null at the top of your class, I think this could be the cause of your duplicate, I would remove the = null from that declaration.

Persistent Music have the music script attached


should i change the name in Music Player? (I’ll change songs later so there will be a song for only 2 level for song)

yeaaah 3 problems down, 1 to go :slight_smile: now I only have the line 27 on the music script

 if (thisLevelMusic)
        {
            audioSource.clip = thisLevelMusic; //this is line 27 
            audioSource.loop = true;
            audioSource.Play();
        }
1 Like

Ok, so if it is that line that is erroring and you are still getting a NullReferenceException error then it must be the audioSource which is null, as you are already checking to see if thisLevelMusic is not null in that if statement.

You could test this again using another Debug.Log statement;

if(thisLevelMusic)
{
    if(audioSource)
    {
        Debug.Log("I am an AudioSource");
    }

    audioSource.clip = thisLevelMusic; //this is line 27 
    audioSource.loop = true;
    audioSource.Play();
}

If you don’t see this message then we have definitely confirmed the lack of an initialised audioSource variable at this point in your code, if this is the case, try giving this a go within your Start method;

audioSource = gameObject.GetComponent<AudioSource>();

instead of;

audioSource = GetComponent<AudioSource>();

Also, something maybe worth checking, I saw on your other screenshot that you had multiple Persistant Music GameObjects, where-as there should only be one, from memory in Glitch Garden it is added to the splash scene, because it doesn’t get destroyed on the load of a new scene it will persist throughout the life time of the game. As such, you should only have one. It would be worth checking your other scenes (all of them) to ensure that you haven’t added one by accident to another scene, if you have, when your code runs you may find where you find the MusicPlayer, you are actually getting the wrong one.

no message was shown in the console so i changedaudioSource = GetComponent<AudioSource>();
with audioSource = gameObject.GetComponent<AudioSource>(); but the problem is still there. I’ve searched for other instances of PersistantMusic but that’s the only copy in the game. The only bad thing is that when i go to the options scene and come back to start menù the game create another PersistantMusic . Maybe is that the problem


image
image (and so on)

You’ll have to help me a bit here as its been a while, but is your PersistantMusic GameObject on your Start scene?

I thought there was a Splash scene which this was added to instead, it does a fade into the game, maybe you aren’t at that lecture yet?

I have the persistant music in the start scene, not in the splash screen should i put that in the splash?
I’m in the last video of the glitch garden (the one with win tag).

1 Like

From memory I think it was on the Splash scene. This scene is only ever loaded once (per load of the game), there should only then be one instance of the PersistantMusic GameObject. At the moment, because you have it on the Start scene, and it is set to DontDestroyOnLoad, each time you return to the Start scene it creates a new one. I think this section was covering the concept of having just the one instance of a GameObject but without using the Singleton pattern from a previous section.

Move it on to the Splash scene instead and let’s see if that gets rid of the duplication issue, which may very well resolve the other issue. My thinking is that the code to Find a GameObject of type MusicPlayer is returning the first it finds, which may not be a correctly initialised one. Let’s see! :slight_smile:

(p.s sorry the lengthy delay responding, I was helping my son with his homework :slight_smile: )

1 Like

thank you Rob!!! the problem was that :smiley: . If you’re helping your son like you did to me he’s going to get 100/100 in his homework

1 Like

Great, glad you can move forward again!

Thank you, very kind :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms