DontDestroyOnLoad
で指定した以上をシーンを遷移してもオブジェクトは削除されず残り続けるので、どこかで明示的にGameObject.Destroy
を呼んでオブジェクトを削除しなければなりません。
簡単な方法としてはどこかのstatic変数にDontDestroyOnLoad
したオブジェクトを集めておき、スタート画面に戻るタイミングなどで削除するようにすればいいと思います。
まず、このようなクラスを用意します。
c#
1using UnityEngine;
2using System.Collections.Generic;
3
4class DontDestroyObjectManager {
5 static List<GameObject> dontDestroyObjects = new List<GameObject>();
6
7 static public void DontDestroyOnLoad(GameObject obj) {
8 Object.DontDestroyOnLoad(obj);
9 dontDestroyObjects.Add (obj);
10 }
11
12 static public void DestoryAll() {
13 foreach (var obj in dontDestroyObjects) {
14 GameObject.Destroy (obj);
15 }
16 dontDestroyObjects.Clear ();
17 }
18}
そして、DontDestroyOnLoad
の代わりにDontDestroyManager.DontDestroyOnLoad
を呼びます。
それらのオブジェクトを削除したいとき(スタート画面に戻るとき、とか?)に、DontDestroyManager.DestroyAll
を呼ぶようにします。
c#
1if (nextScene == "Start") {
2 DontDestroyManager.DestroyAll ();
3}
4SceneManager.LoadScene (nextScene);
こんな感じでどうでしょうか?
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/08/30 13:31