2013年4月20日 星期六

獨一無二的參考 - Singleton

架構程式的過程中,要取得玩家血量、速度,還是場面上的敵人數量、資料,會需要將很多物件關聯起來。只是在關聯參考的時候,管理上往往變的很麻煩。所以要創造一個環境去讓程式可以找到所有可能需要被參考的資料,但又為了這個環境,又需要去創造更多的物件出來。

要解決這個問題,在程式的架構技巧上,有一個很常被使用的方法 - Singleton。

這個架構指的是這項物件在環境中是獨一無二的,例如單機遊戲的分數資料、殺敵數等等。 在這個情況下,我們便可以使用這個技巧來簡化我們的程式的架構。

Singleton 的基本範例

/*
*Author YEN LIN WU (Idleman) 2013.04.20
*/
using UnityEngine;
using System.Collections;
public class MySingleton : MonoBehaviour {
#region Variables
private static MySingleton s_singleton = null;
#endregion
#region Properpty
public static MySingleton Singleton {
get {
// 沒有的話就試圖尋找
if( s_singleton == null ) {
// 先從遊戲中物件搜尋
s_singleton = GameObject.FindObjectOfType(typeof(MySingleton)) as MySingleton;
// 還是找不到就自己做一個
if( s_singleton == null ) {
GameObject go = new GameObject("MySingleton");
s_singleton = go.AddComponent<MySingleton>();
}
}
return s_singleton;
}
}
#endregion
#region Behaviour
private void Awake() {
// 防錯用,摧毀掉多餘的物件
if( MySingleton.Singleton != this ) {
Destroy(this);
return ;
}
}
#endregion
}
view raw MySingleton.cs hosted with ❤ by GitHub


延伸為遊戲資料的範例
/*
*Author YEN LIN WU (Idleman) 2013.04.20
*/
using UnityEngine;
using System.Collections;
public class MyGameData : MonoBehaviour {
#region Variables
private static MyGameData s_singleton = null;
public string m_id = "Idleman";
public int m_score = 0;
public int m_kills = 100000;
#endregion
#region Properpty
public static MyGameData Singleton {
get {
if( s_singleton == null ) {
s_singleton = GameObject.FindObjectOfType(typeof(MyGameData)) as MyGameData;
if( s_singleton == null ) {
GameObject go = new GameObject("MyGameData");
s_singleton = go.AddComponent<MyGameData>();
}
}
return s_singleton;
}
}
#endregion
#region Behaviour
private void Awake() {
if( MySingleton.Singleton != this ) {
Destroy(this);
return ;
}
}
#endregion
}
view raw MyGameData.cs hosted with ❤ by GitHub


這時候如果要設定玩家的資料,就只要做這樣的動作

分數 + 20
MyGameData.Singleton.m_score += 20;
殺敵數 + 1
MyGameData.Singleton.m_kills++;

很簡單吧~

沒有留言:

張貼留言