1.储存文件的生成和读取(通用)
1.数据例子(程序需要的数据,在这是为了下面的例子)
[ Serializable ]
public class DataJson {
public string name;
public int age;
}
2.生成储存文件
引用: using System.IO; 保存位置:Path =Application.steamingAssetsPath+“名称” (SteamingAssets文件下,没有需要自己建,打包后依旧调用,在Assets下) 创建文件语句:File.Create(Path) 数据转换为Json: _Json = JsonUtility.ToJson(数据,true);
3.写入数据到文件
File.WriteAllText(Path,_Json);
4.读取文档中的数据
流程:获得数据(string类型)——>转化为数据 获取数据:string _json =File.ReadAllText(位置); 转化为数据: JsonUtility.FromJson<对象>(_json);
using System. Collections;
using System. Collections. Generic;
using System;
using System. IO;
using UnityEngine;
[ Serializable ]
public class DataJson {
public string name;
public int age;
}
public class CreatJsonTest : MonoBehaviour {
DataJson _dataJson;
start ( ) {
_dataJson = new DataJson ( ) ;
SaveJson ( ) ;
ReadJson ( ) ;
}
public void SaveJson ( ) {
if ( ! File. Exists ( Path) )
{
File. Create ( Path) ;
}
File. WriteAllText ( Path, JsonUtility. ToJson ( _dataJson, true ) ) ;
}
public void ReadJson ( ) {
string _json = File. ReadAllText ( Path) ;
_dataJson = JsonUtility. FromJson < DataJson > ( _json) ;
Debug. Log ( _dataJson. name) ;
}
}