【发布时间】:2016-08-14 12:05:49
【问题描述】:
我正在制作一款塔防游戏。在第一个版本中,我使用简单的文本格式来表示关卡。这是非常基本的,每次我添加新的级别属性时都必须维护解析过的内容。我发现了序列化和写入二进制文件的加载和保存。为此,我有一个可序列化的类,如下所示:
[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);
}
}
这是编译器错误:
Assets/Tower Defense Assets/Scripts/Utilities/LevelManagerEditor.cs(17,5): 错误 CS1525: Unexpected symbol `
当我双击它时,它会将我指向 OnInspectorGUI() 中的 LevelData levelData; 声明
我不明白这个错误。请帮忙。谢谢:)
【问题讨论】: