Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity MissingReferenceException when loading same scene for second time

Tags:

c#

unity3d

I'm trying to create Arkanoid 3d game using Unity with C#. I've created simple Menu (Scene 0), where I can start my game, my main scene where actual game takes place(Scene 1) and Scoreboard (Scene 2), which is shown after losing all 3 balls Player has at start. After pressing any key i go back to Menu and can start game again. And this is where problem begins.

During second game after loosing 1st ball, my game goes crazy. I get loads of "MissingReferenceException"s like one below (but some linked to other objects (like GUIText's etc):

MissingReferenceException: The object of type 'Player' has been destroyed but
you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Player.BallLost () (at Assets/Player/Player.cs:164)
GameEventManager.TriggerBallLost () (at Assets/Menagers/GameEventManager.cs:30)
Ball.Update () (at Assets/Ball/Ball.cs:47)

I noticed loads of MissingReferenceExceptions that are casued by not assigning variables. But this feels kinda diffrent for me since it all works perfectly during "1st play". What can cause this problem? I cheked in inspector after launching game for the second game and all variables are assigned to objects.

I'm not sure if shoudl insert game code since it has grown rather big and is split into >10 scripts.

like image 285
user2091377 Avatar asked Feb 20 '13 13:02

user2091377


People also ask

Can you load multiple scenes unity?

Handling multiple scenes in the editorWith Unity 5+, simply drag and drop a scene to your hierarchy panel and it will automatically be open in additive mode. This way, you are essentially loading up a new set of objects, scripts, cameras, lights, etc.

How do I make a second scene in unity?

Open the New Scene dialog (menu: File > New Scene or Ctrl/Cmd + n). Select a template from the list. If you want Unity to load the new Scene additively (see note below), enable Load Additively. Click Create to create Scene.


1 Answers

In my case, the problem were two static events. One assigned to call a method whenever it was raised (created by another class), and one created in this class to inform other classes for the occurance of something.

So I just added the following two in the OnDestroy() method:

OtherClass.onNewX_event -= X_eventHandler;

for the fist one (where OtherClass was the other class which was raising the onNewX_event and the current class was handlening it)

onThisClassEvent = null;

for the event created and raised in this class.

like image 106
Pontios Avatar answered Sep 28 '22 09:09

Pontios