Roba Memo - 素人のUnity覚書と奮闘記

素人のUnity覚書と奮闘記

Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)

エラー内容

Some objects were not cleaned up when closing the scene. (Did you spawn new GameObjects from OnDestroy?)

原因と対処方法

OnDestroy時にInstantiateでGameObjectを配置するとでるエラー。
OnDestroyではInstantiateしないようにする。

変更前

   void Method ()
    {
        //何からの処理の後にOnDestroyを実行

        OnDestroy ();
    }

    void OnDestroy ()
    {
        //配置 OnDestroy内に書かれたInstantiateがエラーの原因
        GameObject prefab = Resources.Load ("prefab") as GameObject;
        GameObject obj = Instantiate (prefab);
        obj.transform.position = transform.position;

        //その他の処理

        //破棄
        Destroy (gameObject);
    }

変更後

   void Method ()
    {
        //何からの処理に続けてInstantiateを実行

        //配置
        GameObject prefab = Resources.Load ("prefab") as GameObject;
        GameObject obj = Instantiate (prefab);
        obj.transform.position = transform.position;

        OnDestroy ();
    }

    void OnDestroy ()
    {
        //その他の処理

        //破棄
        Destroy (gameObject);
    }