想要实现的功能为鼠标点击路面生成路点,然后进行导航,把路点信息写成list<vector3>进行保存到json中,然后再次打开程序并读取json,依然是自己所选择的路点信息
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using LitJson;
//先写一个路点类
public class Waypoint
{
public double WaypointX { get; set; }
public double WaypointY { get; set; }
public double WaypointZ { get; set; }
}
//存储路点对象的list
List<Waypoint> WayPos = new List<Waypoint>();
//保存路点的方法
public void Save(){
// N.NavTransform为另一个脚本的list<vector3>里面保存着路点信息,鼠标点击一下生成一个路点
for (int i = 0; i < N.NavTransform.Count; i++)
{
Waypoint waypoint = new Waypoint();
waypoint.WaypointX = N.NavTransform[i].x;
waypoint.WaypointY = N.NavTransform[i].y;
waypoint.WaypointZ = N.NavTransform[i].z;
//把路点对象加入到列表中
WayPos.Add(waypoint);
//轉json
string json = JsonMapper.ToJson(WayPos);
//寫入路徑
string path = Application.dataPath + "/Resources/WayPoints.txt";
//寫入json
StreamWriter sw = new StreamWriter(path);
sw.Write(json);
//第五步:关闭(此步必不可少)
sw.Close();
}
}
//用一个list<Waypoint>的列表去接收路点对象
List<Waypoint> Way = new List<Waypoint>();
/// 從json中讀取坐標信息
public void ReadJson() {
//第一步 读取路径
StreamReader sr = new StreamReader(Application.dataPath + "/Resources/WayPoints.txt");
string jsondata = sr.ReadLine();
//第二步:将json文本转换成对象
Way = JsonMapper.ToObject<List<Waypoint>>(jsondata);
for (int i = 0; i < Way.Count; i++)
{
Debug.Log("X是:" + Way[i].WaypointX + " Y是:" + Way[i].WaypointY + " Z是:" + Way[i].WaypointZ);
}
}
得到这些点的信息,然后把点再次存入到一个list<vector3>的列表中,可以再次导航。