场景卸载时的MissingReferenceException

时间:2016-04-27 16:24:18

标签: unity3d transform scene

我希望在卸载当前运行场景时存储我的数据。为此我写了以下代码:

void OnDisable ()
 {
     BackUpPuzzleData();
 }

 public void BackUpPuzzleData ()
 {
     if (DataStorage.RetrievePuzzleStatus (difficultyLevel, puzzleId) == Constants.PUZZLE_NOT_OPENED
         && DataStorage.RetrievePuzzleStatus (difficultyLevel, puzzleId) != Constants.PUZZLE_COMPLETED)
         DataStorage.StorePuzzleStatus (difficultyLevel, puzzleId, Constants.PUZZLE_RUNNING);

     if (DataStorage.RetrievePuzzleStatus (difficultyLevel, puzzleId) == Constants.PUZZLE_RUNNING)
         StorePuzzleData ();
 }


 private void StorePuzzleData ()
 {
     DataStorage.StorePuzzleTimePassed (difficultyLevel, puzzleId, GameController.gamePlayTime);

     foreach (Transform cell in gridTransform) {
         CellInformation cellInfo = cell.GetComponent<CellInformation> ();
         if (cellInfo != null) {
             CellStorage.StorePuzzleCellNumber (difficultyLevel, puzzleId, cellInfo.RowIndex, cellInfo.ColIndex, cellInfo.number);
             CellStorage.StorePuzzleCellColor (difficultyLevel, puzzleId, cellInfo.RowIndex, cellInfo.ColIndex, cellInfo.CellColor);
             CellStorage.StorePuzzleCellDisplayColor (difficultyLevel, puzzleId, cellInfo.RowIndex, cellInfo.ColIndex, cellInfo.CellDisplayColor);
         }
     }
 }

但是当那时调用OnDisable方法时控制台会给我以下错误:

enter image description here

我已经在项目设置中设置了脚本的执行顺序,那么为什么我会收到这种错误?

目标:基本上我想保存当前的游戏数据,这样当玩家返回时,他可以再次从他离开游戏开始。

2 个答案:

答案 0 :(得分:1)

我有一个建议,不是在场景卸载时保存,而是每次玩家移动时都可以保存,这样即使游戏崩溃,你也可以从玩家最后一次移动中恢复。

这个场景卸载会自动发生还是会让用户做出任何动作(比如点击按钮)?如果它是一个玩家事件,你应该把你的保存代码放在那个按钮上,因为,据我所知,在你的对象被破坏后会调用OnDisable行为,这使你无法存储他们的数据。

答案 1 :(得分:0)

花了一些时间解决这个问题,现在我能够找出这个问题。我不知道有多少解决方案是正确的,但至少现在为我工作。

我在这里讨论这个问题,因为有些成员会从中得到一些暗示。

在游戏加载时,我用一个单元格的脚本填充了一个列表。网格的每个单元格都有一个附加 CellInformation 的脚本。所以我准备了所有这些单元格的列表。

在游戏禁用时,我从这些脚本中获取值并存储到本地存储中。我可以从列表中访问脚本而不是游戏对象,因为它们已经被破坏了。

void OnDisable ()
{
    StorePuzzleData ();
}

private void StorePuzzleData ()
{
    DataStorage.StorePuzzleTimePassed (difficultyLevel, puzzleId, GameController.gamePlayTime);

    foreach (CellInformation cellInfo in cellInfoList) {
        CellStorage.StorePuzzleCellNumber (difficultyLevel, puzzleId, cellInfo.RowIndex, cellInfo.ColIndex, cellInfo.number);
        CellStorage.StorePuzzleCellColor (difficultyLevel, puzzleId, cellInfo.RowIndex, cellInfo.ColIndex, cellInfo.CellColor);
        CellStorage.StorePuzzleCellDisplayColor (difficultyLevel, puzzleId, cellInfo.RowIndex, cellInfo.ColIndex, cellInfo.CellDisplayColor);
        CellStorage.StorePuzzleCellGroupComplete (difficultyLevel, puzzleId, cellInfo.RowIndex, cellInfo.ColIndex, cellInfo.IsGroupComplete ? 1 : 0);
    }

}

我希望这会给其他程序员一些提示。