Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8899

[Unity] 継承を使ってマネージャーの生成

$
0
0

自分が個人で開発するときによく使う方法です。
各シーンで使う共通のマネージャー(シーン切り替えのマネージャー等)がある時に、わざわざそのマネージャーを各シーンに配置するのは手間なので、マネージャーを生成するスーパークラスを作ります。
今回はSceneManagerを持つゲームオブジェクトのプレハブの生成をするとします。

BaseController.cs

BaseController.cs
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;publicclassBaseController:MonoBehaviour{protectedSceneManagersceneManager;voidAwake(){if(GameObject.FindWithTag("SceneManager")==null){sceneManager=Instantiate("Prefabのパス").GetComponent<SceneManager>();}else{sceneManager=GameObject.FindWithTag("SceneManager").GetComponent<SceneManager>();}}}

少し捕捉

protected SceneManager sceneManager;

継承先でもアクセス出来るようにprotectedにしてます。

if (GameObject.FindWithTag("SceneManager") == null)

実行したシーン内にマネージャーが存在しない場合は生成、既に存在している場合は取得のみ行います。
オブジェクトを検索ではなくタグを検索にしているのは負荷を減らすため。なのでプレハブにタグをつけるように。


あとは各シーンにこのBaseControllerを継承したサブクラスを作ります。
今回はタイトルシーンのコントローラーとします。

TitleController.cs

TitleController.cs
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;publicclassTitleController:BaseController{//シーン毎の処理}

あとは各シーンで共通の処理がある場合はBaseControllerの方に足していけばいいので比較的楽に拡張していけるのではないかなと思います。


Viewing all articles
Browse latest Browse all 8899

Trending Articles