我正在开展一个小型测试项目,其中99.9%的游戏在代码中,0.1%在视觉编辑器中。
我正在为某种塔防创建瓷砖地图。 每个地图都是5/5,并从资源文件夹
中的文本文件加载我不明白为什么但它只能工作一次。 如果我尝试构建2个地图或构建1,销毁它并重建它我得到这个错误:
NullReferenceException:未将对象引用设置为对象的实例 MapBuilder.buildMap(UnityEngine.GameObject parent,.Map map)(at> Assets / script / MapBuilder.cs:21) Map.build(System.String _name)(在Assets / script / Map.cs:39) Main.Start()(在Assets / script / Main.cs:20)
我的主要课程(目前仅为测试创建地图)
public class Main : MonoBehaviour {
GameObject mainObject;
Map map;
// Use this for initialization
void Start () {
mainObject = GameObject.Find("Main");
map = gameObject.AddComponent<Map>();
map.build("map_start");
GameObject map2 = GameObject.Find("map_start1");
Map map2C = map2.AddComponent<Map>();
map2C.build("map_start1");
}
// Update is called once per frame
void Update () {
}
}
我的地图类
public class Map : MonoBehaviour {
public List<GameObject> planes;
public List<List<int>> mapData;
public string mapName;
public void build(string _name)
{
mapName = _name;
if(planes != null)
{
delete();
}
else
{
planes = new List<GameObject>();
mapData = new List<List<int>>();
}
MapBuilder.buildMap(gameObject, gameObject.GetComponent<Map>());
}
private void delete()
{
for(int i = 0; i < planes.Count; i++)
{
Destroy(planes[i]);
}
mapData.Clear(); //do not clear capacity! only clear element (avoid reallocating the memory)
planes = new List<GameObject>();
mapData = new List<List<int>>();
}
}
这是我有错误的部分
public const float height = -2;
public static Map buildMap(GameObject parent, Map map)
{
//get the stream reader ready
FileInfo sourceFile = null;
StringReader reader = null;
Debug.Log(map.mapName);
//load
TextAsset mapDataStream = (TextAsset)Resources.Load(map.mapName, typeof(TextAsset));
//Debug.Log(mapDataStream.text);
//read
reader = new StringReader(mapDataStream.text);
for(int x = 0; x < 5; x++)
{
string txt = reader.ReadLine();
map.mapData.Add(new List<int>());
//get height data
for(int y = 0; y < 5; y++)
{
map.mapData[x].Add(0);
map.mapData[x][y] = 49 - txt[y];
}
}
mapDataStream = null;
reader.Close();
错误在这一行: reader = new StringReader(mapDataStream.text);
在不使用编辑器的情况下进行游戏需要更多的知识,到目前为止我学到了很多东西。 但这是我自己找不到解决方案的第一个错误
这就是地图的样子
http://i.stack.imgur.com/ouGMr.png
(内联图片需要10点声望)
我从文本文件中获取数据,如下所示: 00000 11111 00000 11011 11111
我自己创建了网格(原始平面每个单元有2个三角形,修改它们将是无用的,我有2个三角形)
到目前为止还没有纹理。这将在稍后添加
玩家将能够建立自己的地图进行防守。他将能够添加一定数量的多种形式的地图,他将能够旋转它们等等...... 下一步是添加路径查找以验证玩家设置的地图。
感谢您的帮助
答案 0 :(得分:0)
如果您查看以下行:
TextAsset mapDataStream = (TextAsset)Resources.Load(map.mapName, typeof(TextAsset));
通过调试代码;逐行逐步执行代码。确定mapDataStream
是否NULL
,因为如果是,则下一行代码将抛出NullReferenceException
,因为您尝试读取空对象的属性。
在Mono中,您可以按照他们的指南进行调试,以便轻松浏览代码并发现问题。请参阅此链接https://docs.unity3d.com/Documentation/Manual/Debugger.html
就像你想要调试的行上设一个断点一样简单:
这是一个视频,可以帮助您更好地理解这一点: