Unity 跨场景数据传输

Unity 跨场景数据传输

1.使用单例模式,DontDestroyOnLoad (go);  对象保存信息

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 () {
 
 }


}

2.使用静态字段

using UnityEngine;
using System.Collections;
  //继承 MONO 和不继承数据保存没区别,只是差在,能否拖入场景

//手动拖入场景相当与做了实例化

// 即使手动拖入场景多个,单只有一个静态字段是有作用,对象数据是用多个的public class G :MonoBehaviour
{

//静态的是全局的,和对象没有关系;即使跨场景数据也会保存,静态数据是保存在类的,在静态区

// 静态数据在面板显示不出来的  public static int m;
      //对象数据,有对象才能保存对应的数据;
 public  int Z;
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }

}

3.使用 PlayerPrefs 保存数据

     场景1 set;

PlayerPrefs.SetFloat("hight",10.5f);
PlayerPrefs.SetInt ("age", 100);

PlayerPrefs.SetString ("name", "xixi");

场景2 get

int age= PlayerPrefs.GetInt ("age");
float hight =PlayerPrefs.GetFloat ("hight", 0f);
string name = PlayerPrefs.GetString ("name");

场景1中对数据赋值:

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 () {
 //Debug.Log (C.GetInstance ().age);
 //Debug.Log (G.m);
 //Debug.Log (g.Z);
 }
 public void OnBtnClick() {
 SceneManager.LoadScene ("2");
 }

}


场景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> ();
     //g.Z = 100;

               int age= PlayerPrefs.GetInt ("age");
float hight =PlayerPrefs.GetFloat ("hight", 0f);
string name = PlayerPrefs.GetString ("name");
}

// Update is called once per frame
void Update () {
//Debug.Log (C.GetInstance().age);
Debug.Log (G.m);
//Debug.Log (g.Z);
}
public void OnBtnClick() {
SceneManager.LoadScene ("1");
}

}