圍內 保存用到的數據。html
方法:建立一個GlobalObject,這個GlobalObject須要知足的條件以下:this
在整個遊戲中只有一個,而且是同一個spa
保證只被初始化一次3d
在任何腳本中均可以訪問GlobalObject中存放的數據code
GlobalObject中能夠存聽任何數據htm
實現步驟:遊戲
建立空物體GlobalObjectip
建立GlobalControl C#腳本get
將腳本賦給GlobalObject
it
public class GlobalControl : MonoBehaviour { public static GlobalControl Instance; //要保存使用的數據; public int HP; public int MP; public int EXP; //初始化 private void Awake() { if(Instance==null) { DontDestroyOnLoad(gameObject); Instance = this; } else if(Instance!=null) { Destroy(gameObject); } } }
public class Player:MonoBehaviour { Public int HP; Public int MP; Public int EXP; ......// other functions Public void SavaData() { GlobalControl.Instance.HP=HP; GlobalControl.Instance.MP=MP; GlobalControl.Instance.EXP=EXP; } }
PlayerPrefs類是unity自帶的類,功能是在場景會話之間訪問玩家眷性。
https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
using UnityEngine; using UnityEngine.UI; public class PlayerPrefsDeleteAllExample : MonoBehaviour { int m_Score; void Start() { //Fetch the PlayerPref settings SetText(); } void SetText() { //Fetch the score from the PlayerPrefs (set these Playerprefs in another script). If no Int of this name exists, the default is 0. m_Score = PlayerPrefs.GetInt("Score", 0); } void OnGUI() { //Fetch the PlayerPrefs settings and output them to the screen using Labels GUI.Label(new Rect(50, 130, 200, 30), "Score : " + m_Score); } }