我正在尝试每当玩家到达传送门时保存游戏,然后当游戏停止并且玩家想再次玩时,他可以在开始菜单上按继续按钮以从他上次解锁的级别开始。
以下是教程链接: http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/persistence-data-saving-loading 以下是应该保存游戏的传送门脚本之一:
我开始使用GameControl.control.x,因为在教程中这个方法可以用来加载、保存或添加变量。唯一的区别是所有的操作都需要通过GUI按钮实现。由于control是静态的,所以GameControl.control.levelcount +=1;应该可以正常工作,对吗?
以下是教程链接: http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/persistence-data-saving-loading 以下是应该保存游戏的传送门脚本之一:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class Saving : MonoBehaviour
{
void OnTriggerEnter( Collider other)
{
if(other.gameObject.tag == "Player")
{
GameControl.control.levelcount += 1;
GameControl.control.Save();
}
}
}
没有出现错误。
这是继续按钮的脚本:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class ContinueCS : MonoBehaviour {
void OnMouseUp(){
GameControl.control.Load();
int levelcount = GameControl.control.levelcount;
if(levelcount == 0)
{
Application.LoadLevel("Level1");
}
else
Application.LoadLevel(levelcount);
}
}
没有错误
以下是基于教程的脚本:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class GameControl : MonoBehaviour {
public static GameControl control;
public float score;
public int levelcount;
void Awake () {
if(control == null)
{
DontDestroyOnLoad(gameObject);
control = this;
}
else if(control != this)
{
Destroy(gameObject);
}
}
public void Save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
PlayerData data = new PlayerData();
data.score = score;
data.levelcount = levelcount;
bf.Serialize(file, data);
file.Close();
}
public void Load()
{
if(File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
score = data.score;
levelcount = data.levelcount;
}
}
}
[Serializable]
class PlayerData
{
public float score;
public int levelcount;
}
编辑:这是当前的脚本,仍然无法加载最后一个解锁的关卡,它会一直加载第一关,如果我从continuescript中删除if语句,只留下这个:
void OnMouseUp(){
GameControl.control.Load();
int levelcount = GameControl.control.levelcount;
Application.LoadLevel(levelcount);
it simply does nothing so i'm guessing the levelcount just isn't adding up.
我开始使用GameControl.control.x,因为在教程中这个方法可以用来加载、保存或添加变量。唯一的区别是所有的操作都需要通过GUI按钮实现。由于control是静态的,所以GameControl.control.levelcount +=1;应该可以正常工作,对吗?
BinaryFormatter
了!请改用 XML、JSON 或类似的格式。详情请见:二进制序列化程序的安全性指南。 - derHugo