1. 程式人生 > >unity3d_場景間資料傳遞

unity3d_場景間資料傳遞

在遊戲專案中,常常會使用到使用者資訊,獲取資訊當然可以從資料庫中獲取。但是對場景多的遊戲這樣做是不正確的,那麼我我們就需要再第一次獲取使用者資訊之後,

同時在其它的場景中共享使用者資料,避免對伺服器增加負擔。好的!現在上圖

首先新建第一個場景,命名為one


場景中物體如下:


接著我們新建第二個場景:two

其中場景物件如下:


這樣做一個簡單的區分,以便測試。

製作思想:

在前一個場景中,新增新的EmptyGameObject,同時製作指令碼PersistentData.cs,在指令碼中新增一些全域性變數。在遊戲載入下一個場景的時候,使用

Object.DontDestroyOnLoad()方法進行保護。使得有關的資料得以持久化!

1、PersistentData.cs

using UnityEngine;
using System.Collections;


public class PersistentData : MonoBehaviour {


public  string userName="";
public  string pwd="";
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

if (Application.isLoadingLevel)
   Object.DontDestroyOnLoad(gameObject);
}


}

在場景one中,新增空遊戲物體,同時附加如上的程式碼.

同時呢,在場景的相機上新增user.cs檔案

程式碼如下

using UnityEngine;
using System.Collections;


public class user : MonoBehaviour {


public float width=0.0f;

public float height=0.0f;
public string levelName="";
private string _name="";
private string _pwd="";
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}

void OnGUI() {
 
GUILayout.BeginVertical(GUILayout.Width(200));
GUILayout.BeginHorizontal(GUILayout.Width(200));
GUILayout.Label("Name:");
_name= GUILayout.TextField(_name,10);
GUILayout.EndHorizontal();

GUILayout.BeginHorizontal(GUILayout.Width(200));
GUILayout.Label("passWord:");
_pwd= GUILayout.TextField(_pwd,10);
   GUILayout.EndHorizontal();

if (GUILayout.Button("login",GUILayout.Width(80),GUILayout.Height(60)))
{
//save data 儲存資料到PersistentData的變數中
GameObject.Find("data").GetComponent<PersistentData>().userName = _name;
GameObject.Find("data").GetComponent<PersistentData>().pwd = _pwd;
Application.LoadLevel("two");
}
GUILayout.EndVertical();

}
}

然後在場景two中,給相機新增上PersistentDataGetting.cs檔案

程式碼如下:

using UnityEngine;
using System.Collections;


public class PersistentDataGetting : MonoBehaviour {


private string userName="";
private string pwd="";

private PersistentData pdScript;
// Use this for initialization
void Start () {
 pdScript = GameObject.Find("data").GetComponent<PersistentData>();
 userName = pdScript.userName;
 pwd = pdScript.pwd;
}

// Update is called once per frame
void Update () {

}

void OnGUI(){

               //使用者資訊顯示
GUI.Label(new Rect(Screen.width/2,Screen.height/2,100,30),userName);
GUI.Label(new Rect(Screen.width/2, Screen.height/2+40,100,30), pwd);
}
}

最終效果:


結束語:

當然資料持久話的方式還有很多,這是其中一種,各有各的優缺點,要根據你儲存的資料而定了。

歡迎大家加入夢想之家 遊戲討論群 63438968    175492844  

Enjoy!