Skip to content

Instantly share code, notes, and snippets.

@yuw-unknown
Created August 14, 2017 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuw-unknown/642ffbd8899510839830cbe77562a5d6 to your computer and use it in GitHub Desktop.
Save yuw-unknown/642ffbd8899510839830cbe77562a5d6 to your computer and use it in GitHub Desktop.
MonoBehaviourの親クラスSample
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BaseMonoBehaviour : MonoBehaviour {
// -----------------------------------------
// Instance
// -----------------------------------------
//初期化したかどうかのフラグ(一度しか初期化が走らないようにするため)
private bool _isInitialized = false;
// -----------------------------------------
// Lifecycle
// -----------------------------------------
/**
* 初期化(Awake時かその前の初アクセス、どちらかの一度しか行われない)
*/
protected virtual void Init() { }
/**
* sealed overrideするためにvirtualで作成
*/
protected virtual void Awake() { }
void Start() { }
void Update() { }
/**
* 初期化が必要であればoverrideして利用
*/
public void InitIfNeeded() {
if (_isInitialized) {
return;
}
Init();
_isInitialized = true;
}
// -----------------------------------------
// Position Utility
// -----------------------------------------
/**
* TransformのPositionを弄る際、直接編集できないので、直接いじれるようにする機能
* Ex:
* PositionX += 0.1f; // this.transform.x += 0.1;
*/
protected Vector3 Position
{
set { this.transform.position = value; }
get { return this.transform.position; }
}
protected float PositionX
{
set { Position = new Vector3(value, Position.y, Position.z); }
get { return Position.x; }
}
protected float PositionY
{
set { Position = new Vector3(Position.x, value, Position.z); }
get { return Position.y; }
}
protected float PositionZ
{
set { Position = new Vector3(Position.x, Position.y, value); }
get { return Position.z; }
}
}
// -----------------------------------------
// シングルトン設計
// このクラスを継承すると自動でシングルトン設計になります
// -----------------------------------------
/**
* 高速化シングルトン
* GameObjectでインスタンスを作成する際に利用します。
* GameObject登録しないインスタンスの場合は、動かない
*/
public class BaseSingletonMonoBehaviourOnGameObject<T> : BaseMonoBehaviour where T : BaseMonoBehaviour {
private static T _instance;
//インスタンスを外部から参照する用(getter)
public static T Instance {
get {
if (_instance == null) {
//シーン内からインスタンスを取得
_instance = (T)FindObjectOfType(typeof(T));
//シーン内に存在しない場合はエラー
if (_instance == null) {
Debug.LogError(typeof(T) + " is nothing");
} else {
_instance.InitIfNeeded();
}
}
return _instance;
}
}
// -----------------------------------------
//初期化
// -----------------------------------------
protected sealed override void Awake() {
//存在しているインスタンスが自分であれば問題なし
if (this == Instance) {
return;
}
//自分じゃない場合は重複して存在しているので、エラー
Debug.LogError(typeof(T) + " is duplicated");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment