AudioSource missing reference after SceneManager.LoadScene
Hi there,
I am encountering the weirdest issue, that I will try to break down in the easiest way possible. My game is a one scene only. Many objects in this scene, all with different components in them. The game runs fine in editor, compiles just fine as well. When I run the game (regardless of the platform), everything is perfect, except that, when the player dies I use SceneManager.LoadScene() to reload the current scene. However, while level loading works fine, I suddenly gets my audio source on one of my object to throw a missing reference (component destroyed) when I try to access it in my script ( as = GetComponent() ). I checked in the editor after reloading my scene and the audio source is definitely there.
If I quit the game completely and re-launch, everything is fine again. I tried my ways of tricking the engine to re-load completely (for example, I load a n empty scene which purpose is to load the main scene again) to no avail. Note that this is happening in the editor AND on the final build.
Anyone already encountered these? I assume there is a memory issue.
Okay - this is actually happening with more than the AudioSource. I "fixed" the audio source problem by checking if the variable holding reference to the component is null before playing the sound and if it is re-assigning it. However, I now get the same error for the script itself - which doesn't makes sense because obviously it goes into the script so...
Answer by aur8l · Jul 17, 2017 at 06:36 AM
Fixed it. Using delegate to listen to events can be tricky. You really need to unregister when objects are destroyed. Keen to get an explanation if someone can provide it :)
Answer by Kirbside · Jun 14, 2018 at 02:00 PM
My situation: I have a prefab with an AudioSource attached. When i instantiate the prefab at runtime i noticed that the AudioSoure would get removed from the prefab. What I did to overcome this issue is to add a second AudioSouce, because i noticed that the first one gets removed and the second one stays with the prefab upon instantiation. Hope this helps!
Your answer
![](https://koobas.hobune.stream/wayback/20220612130426im_/https://answers.unity.com/themes/thub/images/avi.jpg)