我正在制作塔防游戏。在第一个版本中,我使用了简单的文本格式。它非常基础,每次添加新的level属性时都必须保持解析。我发现了序列化和写入加载并从/向二进制文件保存。为此,我有一个可序列化的类,如下所示:
[Serializable]
public class LevelData {
public string filename;
public List<List<Tile>> grid;
public List<Vector2> waypoints;
public int width;
public int length;
public Vector2 startPos;
public Vector2 finishPos;
public List<TowerInfo> towers;
public List<WaveData> waveChain;
}
现在我想在我的LevelManager中添加一个编辑器脚本,解析旧的文本文件格式并将其转换为二进制格式。这是我的编辑器脚本:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(LevelManager))]
[CanEditMultipleObjects]
public class LevelManagerEditor : Editor {
public string levelFilename;
public override void OnInspectorGUI() {
DrawDefaultInspector();
if(GUILayout.Button("Load level " + levelFilename + " and serialize")) {
LevelData levelData;
ParseFromFile(out levelData);
Debug.Log("Parsing " + levelFilename + " successful!");
SaveLevel(levelData);
Debug.Log("Saved serialized level");
}
}
private void ParseFromFile(out LevelData levelData) {
levelData = new LevelData();
levelData.filename = levelFilename;
System.IO.StreamReader file = new System.IO.StreamReader(levelFilename + ".txt");
string line;
int y = 0;
while ((line = file.ReadLine()) != null) {
if (line[0] == '#') break;
List<Tile> row = new List<Tile>();
for (int x = 0; x < line.Length; x++) {
switch(line[x]) {
case '.':
row.Add(Tile.NORMAL_BRICK);
break;
case 'P':
row.Add(Tile.PATH_BRICK);
break;
case 'S':
row.Add(Tile.START_BLOCK);
levelData.startPos = new Vector2(x, y);
break;
case 'F':
row.Add(Tile.FINISH_BLOCK);
levelData.finishPos = new Vector2(x, y);
break;
default:break;
}
}
levelData.grid.Add(row);
levelData.width = row.Count;
y++;
}
levelData.length = y;
while((line = file.ReadLine()) != null) {
levelData.waypoints.Add(ParseWaypoints(line));
}
file.Close();
}
private Vector2 ParseWaypoints(string line) {
string[] tokens = line.Split(' ');
return new Vector2(int.Parse(tokens[0]), int.Parse(tokens[1]));
}
private void SaveLevel(LevelData levelData) {
string pathToLevel = Application.persistentDataPath + "/" + levelData.filename + ".dat";
FileStream file = File.Create(pathToLevel);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(file, levelData);
}
}
这是编译器错误: 资产/塔防资产/脚本/公用事业/ LevelManagerEditor.cs(17,5):错误CS1525:意外符号`&lt; internal&gt;'
当我双击它时,它指向OnInspectorGUI()中的LevelData levelData;
声明
我不明白错误。请帮忙。谢谢:)
答案 0 :(得分:1)
我想出来了......我在那条线上有一个不可打印的字符。我不得不删除该行并重写它。