前言
相对于单机游戏或者弱联网游戏会有一个本地数据缓存的问题,联网游戏也会有一些设置需要缓存在本地.也算是记录一下Application.persistentDataPath的方法.
Application.persistentDataPath好像是移动端位移可写可读的路劲,对于热更有独到的地方
本文记录一个移动端写入,读取数据对数据进行加密的操作
一、写入数据
- 使用到LitJson,和ICSharpCode.SharpZipLib.GZip工具
- 先定义一个写入路径,创建一个路径脚本,定义路径
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathRule
{
/// <summary>
/// 本地资源的路径
/// </summary>
public static string ResPath
{
get { return AppPersistentDataPath + "SJ_RES/"; }
}
/// <summary>
/// 本地缓存目录
/// </summary>
public static readonly string AppPersistentDataPath =
#if UNITY_EDITOR
System.Environment.CurrentDirectory + "/";
#elif UNITY_IPHONE
Application.persistentDataPath + "/";
#elif UNITY_ANDROID
Application.persistentDataPath + "/";
#else
System.Environment.CurrentDirectory + "/";
#endif
}
2.创建一个SettingData脚本,这里面有一个加载,保存数据的方法,这两个也可以封装成一个接口给外部调用,加密解密的代码注销掉了,加密解密也只是把数据包装成一个人看不懂的数据,用不到加密的看上面这两个脚本就行了,只不过目前是明文保存
using LitJson;
using System;
using System.Globalization;
using System.IO;
using System.Text;
using UnityEngine;
public class SettingData
{
//用户设置
public static SettingInfo setting { private set; get; }
/// <summary>
/// 初始化系统设置,添加数据,也写个接口在外部添加数据
/// </summary>
public static void InitSystemSet()
{
setting = new SettingInfo();
LoadUserSetting();
Debug.Log(setting.name);
}
/// <summary>
/// 加载txt文件
/// </summary>
private static void LoadUserSetting()
{
try
{
//读取路径文件数据
string settingString = System.IO.File.ReadAllText(PathRule.ResPath + "setting.txt");
//解密转成class,也可以写成通过json吧string转为一个class,我这是把数据保存为一个人看不懂的数据缓存下来,也可以明文保存为
setting = JsonMapper.ToObject<SettingInfo>(settingString);
//setting = CodeUtil.ToObject<SettingInfo>(CodeUtil.Decode(settingString));
//第一次加载报空,创建这个class,方便下面添加数据
if (setting == null)
setting = new SettingInfo();
}
catch (Exception e)
{
setting = new SettingInfo();
}
}
//保存txt文件
public static void SaveUserSetting()
{
//判断文件夹是否存在
if (!Directory.Exists(PathRule.ResPath))
{
//不存在创建文件夹
Directory.CreateDirectory(PathRule.ResPath);
}
//忘路径txt里面写入数据,如果txt不存在创建文件并写入
System.IO.File.WriteAllText(PathRule.ResPath + "setting.txt" , JsonMapper.ToJson(setting), Encoding.UTF8);
//下面这个是封装的加密,解密方法
//System.IO.File.WriteAllText(PathRule.ResPath + "setting.txt" , CodeUtil.Encode(CodeUtil.ToJson(setting)));
}
}
/// <summary>
/// 保存数据类
/// </summary>
public class SettingInfo
{
public string name;
}
3.使用demo,创建一个Demo脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class demo : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
//初始化数据
SettingData.InitSystemSet();
//给缓存数据进行赋值
SettingData.setting.name = "周亚伟";
//保存数据
SettingData.SaveUserSetting();
}
}
}
4.这样就可以在项目下看到这个新建文件
二、加密.解密
1.创建CodeUtil脚本
主要是使用到了Encode(),Decode()两个方法
里面还用到了其他脚本的一些引用,有些判断被简化了,看个人需求a
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
using System.Security.Cryptography;
using ICSharpCode.SharpZipLib.GZip;
using LitJson;
public class CodeUtil
{
//public static string bytesToString(byte[] bytes)
//{
// return Encoding.UTF8.GetString(bytes);
//}
//public static byte[] stringToBytes(string str)
//{
// return Encoding.UTF8.GetBytes(str);
//}
public static T ToObject<T>(string jsStr)
{
return JsonMapper.ToObject<T>(jsStr);
//return DataSynHelper.ToObject<T>(jsStr);
}
//public static T ToObject<T>(byte[] bytes)
//{
// return DataSynHelper.ToObject<T>(bytesToString(bytes));
//}
public static string ToJson(object o)
{
return JsonMapper.ToJson(o);
//return DataSynHelper.ToJson(o);
}
//public static byte[] ToBytes(object o)
//{
// return stringToBytes(DataSynHelper.ToJson(o));
//}
//public static T Clone<T>(string json)
//{
// return DataSynHelper.ToObject<T>(json);
//}
//public static T Clone<T>(object obj)
//{
// return Clone<T>(ToJson(obj));
//}
static string KEY_64 = "12345678";
static string IV_64 = "87654321";
/// <summary>
/// 加密
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string Encode(string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms , cryptoProvider.CreateEncryptor(byKey , byIV) , CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
return Convert.ToBase64String(ms.GetBuffer() , 0 , (int)ms.Length);
}
/// <summary>
/// 解密
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string Decode(string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
byte[] byEnc;
try
{
byEnc = Convert.FromBase64String(data);
}
catch
{
return null;
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(byEnc);
CryptoStream cst = new CryptoStream(ms , cryptoProvider.CreateDecryptor(byKey , byIV) , CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cst);
return sr.ReadToEnd();
}
//static string intToX(int d)
//{
// return string.Format("{0:X2}" , (byte)d);
//}
//public static string toSignedString(int v)
//{
// if (v >= 0)
// return "+" + v.ToString();
// else
// return v.ToString();
//}
//public static string toSignedString(float v)
//{
// if (v >= 0)
// return "+" + v.ToString();
// else
// return v.ToString();
//}
//public static string toSignedString(string v)
//{
// if (Int32.Parse(v) >= 0)
// return "+" + v.ToString();
// else
// return v.ToString();
//}
//public static Transform FindSkeletonInChildren(Transform ts , String name)
//{
// Queue<Transform> q = new Queue<Transform>();
// q.Enqueue(ts);
// while (q.Count > 0)
// {
// Transform t = q.Dequeue();
// if (t.name == name)
// return t;
// int childCount = t.childCount;
// for (int i = 0; i < childCount; i++)
// {
// q.Enqueue(t.GetChild(i));
// }
// }
// return null;
//}
//public static byte[] Compress(string strData)
//{
// MemoryStream ms = new MemoryStream();
// GZipOutputStream compressedzipStream = new GZipOutputStream(ms);
// byte[] data = CodeUtil.stringToBytes(strData);
// int size = data.Length;
// compressedzipStream.Write(data , 0 , data.Length);
// compressedzipStream.Finish();
// compressedzipStream.Close();
// byte[] result = ms.ToArray();
// Debug.LogWarning("compress rate " + ((float)size / result.Length));
// return result;
//}
//public static string Decompress(byte[] data)
//{
// int size_before = data.Length;
// MemoryStream ms = new MemoryStream(data);
// GZipInputStream compressedzipStream = new GZipInputStream(ms);
// MemoryStream outBuffer = new MemoryStream();
// byte[] block = new byte[1024];
// while (true)
// {
// int bytesRead = compressedzipStream.Read(block , 0 , block.Length);
// if (bytesRead <= 0)
// break;
// else
// outBuffer.Write(block , 0 , bytesRead);
// }
// compressedzipStream.Close();
// byte[] result = outBuffer.ToArray();
// Debug.LogWarning("Decompress rate " + ((float)size_before / result.Length));
// return CodeUtil.bytesToString(result);
//}
}
加密就是下面这种,不是明文了,一般人也看不懂,但二班的也能看出来
总结
csdn资源下载地址
没了