本次的做业是,修改飞碟程序。它使用如下 JSON 文本控制程序(你能够自由添加内容)
一、远程控制目录(有四个Json文件)
game_info.json - {“version”:1.2 ,”totolRound”:3, …}
disk_level_1.json - {“title”:”Round 1”, “turn”:10, “diskEachTurn”:1, “speedMax”:10, “speedMin”:8, “color”=”gray,red”, … } html
二、修改飞碟程序,并发布web
因为我是二年级生,因此不少大的思路都来源于大三师兄的博客。
尤为是胡江川师兄。他的博客写的十分的完整、易懂。因此这门课在他的博客上面我真的是受益不浅。
传送门:Simba的博客json
好了咱们来看下这一次的做业。要求用json文件来存储游戏的信息。这是一个在实际游戏中常见,也是十分重要的功能。这一次咱们用json简单地模拟一下其读写。并发
其中保存了每一关的信息。包括飞碟的颜色,发射的位置,发射的方向,发射的速度,第几次合等等。根据这些信息在初始化的时候咱们就能够直接读取json文件,提取相应信息,赋值便可。
svg
建立完json文件以后咱们要考虑的问题就是如何将json文件变成data.根据课上的内容以及一些文档的提示。
首先咱们建立一个FileManager.cs的脚本函数
能够经过以下的方法拿到咱们的数据:ui
// 输入关卡文件名,启动协程读取文件
public void loadLevelJson(string name)
{
url = "file://" + Application.dataPath + "/Data/" + name;
Debug.Log(url);
StartCoroutine(LoadLevel());
}
IEnumerator LoadLevel()
{
if (url.Length > 0)
{
WWW www = new WWW(url);
yield return www;
if (!string.IsNullOrEmpty(www.error))
Debug.Log(www.error);
else
scene.stageLevel(www.text.ToString()); // 返回json字符串给scene
}
}
拿到数据后返回给SceneController,里面建立相关的函数对拿到的数据进行赋值。
而在SenceController处赋值方法以下:url
public void stageLevel(string json)
{
//获取相关json数据
LevelData data = LevelData.CreateFromJSON(json);
int emitNum = data.emitNum;
float speed = data.speed;
_judge.disksEachRound = emitNum;
_judge.round = data.round;
//配置发射环境
Vector3 emitPos = new Vector3(data.emitPosX, data.emitPosY, data.emitPosZ);
Vector3 emitDir = new Vector3(data.emitDirX, data.emitDirY, data.emitDirZ);
_gameModel.setting(1, color, emitPos, emitDir.normalized, speed, emitNum);
}
一样的方法适用于disk_level_1.json
这样子咱们就完成了FileManager.cs文件。将其挂载主摄像机上。spa
[SerializeField] Attribute
强制unity去序列化一个私有域.net
这是一个内部的unity序列化功能,有时候咱们须要Serialize一个private或者protected的属性,这个时候可使用[SerializeField]这个Attribute:
在Unity最新的UI系统中,UI属性上方所有添加[SerializeField] ,以下所示
[SerializeField]
private Button btn1;
SerializeField参考文档:
http://game.ceeger.com/Script/Attributes/SerializeField.html
所以,咱们在SceneController中gameinfo和disklevel进行序列化
[SerializeField]
public class GameInfo
{
public string version;
public int totalRound;
public static GameInfo CreateFromJSON(string json)
{
return JsonUtility.FromJson<GameInfo>(json);
}
}
[SerializeField]
public class LevelData
{
public string color;
public int emitNum;
public float emitPosX, emitPosY, emitPosZ;
public float emitDirX, emitDirY, emitDirZ;
public float speed;
public int round;
public static LevelData CreateFromJSON(string json)
{
return JsonUtility.FromJson<LevelData>(json);
}
}
拿到game_info的数据后确定要显示在主界面上。
咱们将这些数据都写在咱们的控制器中,并将其置为Public变量。
public string _version;
public int _totalRound;
public Color color;
而后在UI中对Text进行赋值
string gameinfo = "version : " + SceneController.getInstance()._version;
gameInfoText.text = gameinfo;
roundText.text = "Round: " + queryInt.getRound().ToString() + "/" + SceneController.getInstance()._totalRound;
scoreText.text = "Score: " + queryInt.getPoint().ToString();
小小的游戏展现:能够看到显示了json文件存储的内容,