LoginSignup
29
26

More than 5 years have passed since last update.

Unity C# リロード(初期状態にもどる)的な処理

Last updated at Posted at 2014-08-10

シーンを初期状態に戻したい(読み込んだ状態に戻したい)時は、
以下のように、自身のシーン名を指定した Application.LoadLevel() を利用するとよさそう。

using UnityEngine;

public class Sample : MonoBehaviour {

    void OnGUI() {

        if( GUILayout.Button("Reload") ) {

            Application.LoadLevel("Main"); // シーンの名前かインデックスを指定
        }
    }
}

ただし、シーンの再読み込みだと、
GameObjectはリセットされるけど、スクリプトは残ってしまいます。

僕がよくやる方法としては、

  • インスタンスが複数になると困る部分はシングルトンパターンを使う
  • リセットされたくないGameObjectには以下を指定
using UnityEngine;

public class Sample : MonoBehaviour {

    void Awake () {

        DontDestroyOnLoad(this); // シーン読み込みの際に破棄されなくなる
    }
}

という感じで、プログラム全体を設計しておく。

29
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
26