Why does my sound manager work and then after restarting unity it doesnt?

I have a sound manager which i learnt from a tutorial

it was working, then i saved everything and restarted, and it wasnt working, had the below error.

if i recreate the script and apply it, it works, but as soon as i restart unity and my project, im getting an error:
NullReferenceException: Object reference not set to an instance of an object

and it takes me to this line:

audioSrc.PlayOneShot(raceStart);

here is my entire sound manager script

any ideas why it works and then stops?

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

public class soundManager : MonoBehaviour
{
    public static AudioClip raceStart;

    static AudioSource audioSrc;



    // Start is called before the first frame update
    void Start()
    {

        raceStart = Resources.Load<AudioClip>("racestart");
        audioSrc = GetComponent<AudioSource>();


    }

    // Update is called once per frame
    void Update()
    {
    }

    public static void PlaySound(string clip)
    {

        switch (clip)
        {
            case "racestart":
                audioSrc.PlayOneShot(raceStart);
                break;
        }
    }

}

Well it’s very weird to have this thing be a MonoBehaviour, but then use static properties for your raceStart and audioSrc references. Remove “static” from both of those and I bet it’ll work fine. (Static property values stick around for the lifetime of the app, which is Unity itself when running within the editor, so that’s why it works until you quit.)

Of course you’ve got PlaySound set as static too, so you’ll need to make a few other adjustments. Probably you should be using the Singleton pattern instead.

You’re probably calling PlaySound before Start has run. Maybe the object with this script attached isn’t even in the scene. Add debugging, and also check results of all your GetComponent and Resources.Load calls for null before using them.

ok thanks got it sorted, yes it was played from the wrong objects start function, moved it to where it should be, working fine now so it seems.

You might want to move everything in your Start method here to Awake, so you’re sure it is run before any other object’s Start method if you’re going to play sounds with this from Start.

1 Like