[英]Saving Cube like in Minecraft game
我正在嘗試使用Unity像Minecraft一樣為Android構建游戲。 如何保存進度?
我正在嘗試這段代碼,但是如果我走對了,我還是一無所知。
public class SavePref : MonoBehaviour {
GameObject[] objects;
float x;
float y;
float z;
// Use this for initialization
void Start () {
objects = GameObject.FindGameObjectsWithTag("ObjectSnap");
}
// Update is called once per frame
void Update () {
}
public void Load()
{
foreach (GameObject obj in objects)
{
obj.name = PlayerPrefs.GetString("Ojects");
x = PlayerPrefs.GetFloat("X");
y = PlayerPrefs.GetFloat("Y");
z = PlayerPrefs.GetFloat("Z");
}
}
public void Save()
{
objects = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
Debug.Log(objects.Length);
foreach (GameObject obj in objects)
{
PlayerPrefs.SetString("Objects", obj.name);
Debug.Log(obj.name);
x = obj.transform.position.x;
PlayerPrefs.SetFloat("X", x);
y = obj.transform.position.y;
PlayerPrefs.SetFloat("Y", y);
z = obj.transform.position.z;
PlayerPrefs.SetFloat("Z", z);
Debug.Log(obj.transform.position.x);
Debug.Log(obj.transform.position.y);
Debug.Log(obj.transform.position.z);
}
}
}
原因是您要覆蓋相同的值。
場景中的每個對象都會覆蓋PlayerPerfs的相同“ X”,“ Y”,“ Z”和“ Objects”變量。 因此,如果您只想保存街區頭寸,
場景中的每個塊都必須具有自己的sceneID。
編寫PlayerPerfs時,請使用這些ID。
例如:
public GameObject[] inscene;
void SaveBlock(){
inscene = GameObject.FindGameObjectsWithType("ObjectSnap");
for(int i = 0; i < inscene.Length; i++){
PlayerPerfs.SetFloat(i.ToString() + "_x", x);
PlayerPerfs.SetFloat(i.ToString() + "_y", y);
PlayerPerfs.SetFloat(i.ToString() + "_z", z);
}
PlayerPerfs.SetInt("Count", inscene.Length);
}
void LoadBlocks(){
int count = PlayerPerfs.GetInt("Count");
inscene = new GameObject[count];
for(int i = 0; i < count; i++)
{
float x = PlayerPerfs.GetFloat(i.ToString() + "_x");
float y = PlayerPerfs.GetFloat(i.ToString() + "_y");
float z = PlayerPerfs.GetFloat(i.ToString() + "_z");
inscene[i] = GameObject.CreatePrimitive(PrimitiveType.Cube);
inscene[i].transform.position = new Vector3(x, y, z);
inscene[i].tag = "ObjectSnap";
}
}
此代碼將只保存塊的位置,並使用白色立方體重新創建世界。
如果要保存塊的類型,則應在Load()時將所有類型的塊都設置為prefarb,並實例化預制件。
PS無論如何,這種針對Android的Minecraft克隆的實現非常糟糕。 想象一下,您有一個小塊(32 * 32 * 32)充滿了塊,那么RAM將必須處理內存中的32768個塊(這只會殺死應用程序)。
因此,您必須操作的不是塊,而是操作這些塊的側面,以剔除不可見的側面。
而且您不應該通過PlayerPerfs保存場景信息。 請改用System.IO。 據我所知,PlayerPerfs將信息保存在注冊表中,這對此類數據不利。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.