u3d使用json存储本地数据
本人在使用json遇到各种坑,现在总结一下,免得以后忘记
1. 首先得自定义一个类,*
这个类主要写明数据的类型
using System;
using System.Collections.Generic;
[Serializable]
public class LevelData
{
public int score; //得分
public bool isLock;//是否解锁
public int level;//当前关卡
public int differences;//不同之处的数量
}`
2.然后选择存储的位置
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using LitJson;
public class GameManager : MonoBehaviour
{
static string persistDataPath;//定义路径
private static GameManager instance = null;
public LevelData levelData;
public static GameManager Instance
{
get
{
if (instance==null)
{
GameObject go = new GameObject();
go.name = "GameManager";
instance = go.AddComponent<GameManager>();
DontDestroyOnLoad(go);
}
return instance;
}
}
void Awake()
{
Application.targetFrameRate = 30;
#if UNITY_EDITOR
persistDataPath = Application.streamingAssetsPath + "/Level.json";
//需要在unity的Assets目录下创建一个StreamingAssets的文件夹,在里面放个json文件(在电脑桌面创一个text文本,修改后缀为json就可以了)
#endif
#if !UNITY_EDITOR
persistDataPath = Application.persistentDataPath + "/Level.json";
#endif
// Debug.Log("私人地址" + Application.streamingAssetsPath);
Debug.Log("json地址" + persistDataPath);
if (!File.Exists(persistDataPath))
{
File.Create(persistDataPath);
// Debug.Log("json地址"+persistDataPath);
}
if (instance==null)
{
instance = this;
DontDestroyOnLoad(instance);
}
else
{
Destroy(gameObject);
}
}
这里注意了,Application.streamingAssetsPath和Application.dataPath这两个只能在电脑上读写,
在iOS上不能读写,能不能在安卓,这个不清楚,项目主要做iOS平台。Application.persistentDataPath用于读写,所以一般用Application.persistentDataPath + “/Level.json”,系统会自动创建一个Level的json文件。而其他两个都需要手动创建文件夹和拖动json文件*
3.读写数据存储到json文件里
public void WriteToJson(LevelData _data)
{
levelData = _data;
string d = JsonMapper.ToJson(_data);
if (File.Exists(persistDataPath))
{
File.WriteAllText(persistDataPath, d);
}
}
public void ReadFromJson()
{
string data = File.ReadAllText(persistDataPath);
LevelData d = JsonMapper.ToObject<LevelData>(data);
}
在这里就已经完成了数据的读写了,不管是使用litjson还是u3d自带的JsonUtility,使用方法是一样的
最后强调,在平台上一定得用 Application.persistentDataPath 我在代码上设置了平台宏,使用了Application.streamingAssetsPath,主要是为了方便查看json文件,有没有写入数据
版权声明:本文为qq_35557577原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。