5

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.

4

3 回答 3

5

就我而言,问题是两个静态事件。一个指定在方法被提出时调用(由另一个类创建),一个在此类中创建以通知其他类发生某事。

所以我只是在方法中添加了以下两个OnDestroy()

OtherClass.onNewX_event -= X_eventHandler;

对于第一个(OtherClass 是引发 onNewX_event 并且当前类正在处理它的另一个类)

onThisClassEvent = null;

对于在此类中创建和引发的事件。

于 2017-07-24T19:19:35.010 回答
3

我猜你用过Application.loadLevel(xx)。这是我发现的:

除非您使用静态变量,否则重新加载场景应重置所有变量,因为从逻辑上创建每个对象的新实例会将其值重置为其初始状态。

另一方面,静态变量不会被销毁,因为它们是类的一部分,而不是实例。您必须手动重置这些。

DontDestroyOnLoad()有点不同。它告诉 Unity 在加载新场景时不要破坏对象。所以这些对象也不会被重置,因为它们没有被销毁和重新创建。

重置它们的唯一方法是手动检查并将变量转回某个初始状态。如何做到这一点是您的选择。您可以保存所有初始值,也可以从新实例化的类中复制这些值。

作为补充,我想说如果您使用静态变量,将它们全部放在单例中或将它们更改为非静态变量可能更有用。

于 2013-02-20T14:42:08.113 回答
2

在您的 GameEventManager 类中包含以下函数

public static void Nullify(){
    GameStart = null;
    GameOver = null;
    LevelWon = null; 
    GamePause = null; 
    GameResume = null; 
    BallLost = null;

}

并在加载其他场景之前在 Menu(scene0) 中调用此函数 (GameEventManager.Nullify();) ;

GameEventManager.Nullify();
Application.LoadLevel("Scene1);

希望这有帮助...... :-)

于 2014-12-20T15:33:29.640 回答