(:3[kanのメモ帳]

個人ゲーム開発者kan.kikuchiのメモ的技術ブログ。月木更新でUnity関連がメイン。

(:3[kanのメモ帳]


本ブログの運営者kan.kikuchiが個人で開発したゲームです!

    

OnLevelWasLoadedが非推奨になったからSceneManager.sceneLoadedで置き換えてみる【Unity】


このエントリーをはてなブックマークに追加


この記事でのバージョン
Unity 5.4.0f3


はじめに

Unityを5.4.0f3アップデートしたところ、以下の通りWarningが出ました。


f:id:kan_kikuchi:20160809134220j:plain

This message has been deprecated and will be removed in a later version of Unity.
Add a delegate to SceneManager.sceneLoaded instead to get notifications after scene loading has completed


OnLevelWasLoadedが非推奨になったからSceneManager.sceneLoadedを使えとの事。

警告を無視してOnLevelWasLoadedを使うことも可能ですが、

いつか削除されるかもしれないので素直にSceneManager.sceneLoadedを使う方法に変えてみました。

今回はその方法のご紹介。


SceneManager.sceneLoaded

そもそもSceneManager.sceneLoadedとはなんぞやという話ですが、

名前の通り、シーンをロードし終わった時に呼ばれるイベントです。

Add a delegate to this to get notifications when a scene has loaded


イベントやデリゲートについては以下の記事を参照の事。




実際にSceneManager.sceneLoadedを使って、

OnLevelWasLoadedを書き換えた例が以下の通りです。

/*OnLevelWasLoadedを使った場合*/
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

  private void OnLevelWasLoaded (int level){
    Debug.Log (level);
  }

} 
/*sceneLoadedを使った場合*/
using UnityEngine;
using UnityEngine.SceneManagement;//SceneManagerを使う用
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

  private void Start (){
    SceneManager.sceneLoaded += OnSceneLoaded;//イベントにメソッドを登録
  }

  private void OnSceneLoaded (Scene scene, LoadSceneMode sceneMode){
    Debug.Log (scene.buildIndex);//sceneの番号はscene.buildIndexで分かる
  }

} 


上記の通り、SceneManager.sceneLoadedにメソッドを登録するだけOK。


ただ、注意が必要なのがsceneLoadedが実行されるタイミングです。

実行される順番は

  1. Awake
  2. SceneManager.sceneLoaded
  3. Start

なので、

Startでメソッドを登録すると最初のシーンでは実行されず、

Awakeでメソッドを登録すると最初のシーンでも実行されます。


おわりに

記事の内容と関係ありませんが、

Unity Plusを契約したので、この記事以降の記事はエディターが黒くなります!ヾ( ゚д゚)ノ゛