# 使用单例模式,DontDestroyOnLoad (go); 对象保存信息 ```csharp using UnityEngine; using System.Collections; // 对象数据想被跨场景后保存,只能采用,DontDestroyOnLoad (go); 方法保存数据,数据保存在堆中 // 拖入场景多个,但是只有一个起作用 public class C : MonoBehaviour { public int age; private C(){ } private static C _instance; /// <summary> /// Gets the instance. /// </summary> /// <returns>The instance.</returns> public static C GetInstance(){ GameObject g = GameObject.Find ("InstanceC"); if (g == null) { GameObject go = new GameObject (); go.name = "InstanceC"; DontDestroyOnLoad (go); if (_instance == null) { if (go.GetComponent<C> () == null) { // 通过脚本 自动添加对象,必须先实例化,否则是空,无法保存信息,没有申请空间 _instance = new C (); go.AddComponent<C> (); } } else { return _instance; } } return _instance; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
使用静态字段
using UnityEngine; using System.Collections; // 继承 MONO 和不继承数据保存没区别,只是差在,能否拖入场景 // 手动拖入场景相当与做了实例化 // 即使手动拖入场景多个,单只有一个静态字段是有作用,对象数据是用多个的 public class G :MonoBehaviour { // 静态的是全局的,和对象没有关系;即使跨场景数据也会保存,静态数据是保存在类的,在静态区 // 静态数据在面板显示不出来的 public static int m; // 对象数据,有对象才能保存对应的数据; G g ; // Use this for initialization void Start () { C.GetInstance (); C.GetInstance ().age = 90; G.m = 1000; g = GetComponent<G> (); g.Z = 100; } }
使用 PlayerPrefs
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class D : MonoBehaviour { C cc; G g ; // Use this for initialization void Start () { C.GetInstance (); C.GetInstance ().age = 90; G.m = 1000; g = GetComponent<G> (); g.Z = 100; PlayerPrefs.SetFloat("hight",10.5f); PlayerPrefs.SetInt ("age", 100); PlayerPrefs.SetString ("name", "xixi"); } // Update is called once per frame void Update () { } public void OnBtnClick() { SceneManager.LoadScene ("2"); } }
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class E : MonoBehaviour { public static int m; G g ; // Use this for initialization void Start () { C.GetInstance (); g = GetComponent<G> (); int age= PlayerPrefs.GetInt ("age"); float hight =PlayerPrefs.GetFloat ("hight", 0f); string name = PlayerPrefs.GetString ("name"); } // Update is called once per frame void Update () { } public void OnBtnClick() { SceneManager.LoadScene ("1"); } }