要解決這個問題,在程式的架構技巧上,有一個很常被使用的方法 - Singleton。
這個架構指的是這項物件在環境中是獨一無二的,例如單機遊戲的分數資料、殺敵數等等。 在這個情況下,我們便可以使用這個技巧來簡化我們的程式的架構。
Singleton 的基本範例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
*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 | |
} |
延伸為遊戲資料的範例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
*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 | |
} |
這時候如果要設定玩家的資料,就只要做這樣的動作
分數 + 20
MyGameData.Singleton.m_score += 20;
殺敵數 + 1
MyGameData.Singleton.m_kills++;
很簡單吧~
沒有留言:
張貼留言