unity 存储本地数据
在 Unity 中,如何实现本地数据存储呢?接下来我们将通过代码详细介绍其实现方式。
路径工具类 PathKit
首先,我们创建一个路径工具类 PathKit,用于处理不同平台下的文件路径。
using UnityEngine;
using System.Collections;
// 路径工具类
public class PathKit
{
/** 后缀常量字符 */
public const string SUFFIX = ".txt";
const string PREFIX = "file://";
const string FORMAT = ".unity3d";
public static string RESROOT = Application.persistentDataPath + "/";
/// <summary>
/// 获取 StreamingAssets 路径
/// </summary>
/// <param name="p_filename">文件名</param>
/// <returns>StreamingAssets 路径</returns>
public static string GetStreamingAssetsPath(string p_filename)
{
string _strPath = "";
if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
{
_strPath = "file://" + Application.streamingAssetsPath + "/" + p_filename + ".unity3d";
}
else if (Application.platform == RuntimePlatform.Android)
{
_strPath = Application.streamingAssetsPath + "/" + p_filename + ".unity3d";
}
else if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.IPhonePlayer)
{
_strPath = "file://" + Application.streamingAssetsPath + "/" + p_filename + ".unity3d";
}
return _strPath;
}
/// <summary>
/// 获取操作系统数据路径
/// </summary>
/// <param name="p_filename">文件名</param>
/// <returns>操作系统数据路径</returns>
public static string GetOSDataPath(string p_filename)
{
string path = "";
if (Application.platform == RuntimePlatform.OSXEditor)
{
path = Application.persistentDataPath + p_filename;
}
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
path = RESROOT + p_filename;
}
if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor)
{
path = Application.dataPath + "/cache/" + p_filename;
}
if (Application.platform == RuntimePlatform.Android)
{
path = RESROOT + p_filename;
}
// Debug.LogWarning("===========path:" + path);
return path;
}
/// <summary>
/// 获取 URL 路径
/// </summary>
/// <param name="p_filename">文件名</param>
/// <param name="needPreFix">是否需要前缀</param>
/// <param name="needFormat">是否需要格式</param>
/// <returns>URL 路径</returns>
public static string GetURLPath(string p_filename, bool needPreFix, bool needFormat)
{
string path = "";
if (Application.platform == RuntimePlatform.OSXEditor)
{
path = Application.persistentDataPath + "/" + p_filename;
}
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
path = RESROOT + p_filename;
}
if (Application.platform == RuntimePlatform.WindowsEditor)
{
path = Application.dataPath + "/cache/" + p_filename;
}
if (Application.platform == RuntimePlatform.WindowsPlayer)
{
path = Application.dataPath + "/cache/" + p_filename;
}
if (Application.platform == RuntimePlatform.Android)
{
path = RESROOT + p_filename;
}
if (needPreFix)
{
path = PREFIX + path;
}
if (needFormat)
{
path = path + FORMAT;
}
// Debug.LogWarning("===========path:" + path);
return path;
}
/// <summary>
/// 从路径中获取文件名
/// </summary>
/// <param name="path">文件路径</param>
/// <returns>文件名</returns>
public static string getFileName(string path)
{
string[] _list = path.Split(new char[] { '/' });
if (_list.Length > 0)
{
return _list[_list.Length - 1];
}
else
{
return "";
}
}
/// <summary>
/// 从路径中获取文件目录
/// </summary>
/// <param name="path">文件路径</param>
/// <returns>文件目录</returns>
public static string getFileDir(string path)
{
path = path.Replace("\\", "/");
path = path.Substring(0, path.LastIndexOf("/"));
return path;
}
/// <summary>
/// 如果目录不存在则创建
/// </summary>
/// <param name="path">文件路径</param>
public static void CreateDirIfNotExists(string path)
{
string dir = getFileDir(path);
if (!System.IO.Directory.Exists(dir))
{
System.IO.Directory.CreateDirectory(dir);
}
}
}
方法说明
GetStreamingAssetsPath:根据不同平台获取 StreamingAssets 目录下文件的路径。GetOSDataPath:根据不同平台获取操作系统数据目录下文件的路径。GetURLPath:根据不同平台获取文件的 URL 路径,可选择是否添加前缀和格式。getFileName:从文件路径中提取文件名。getFileDir:从文件路径中提取文件所在目录。CreateDirIfNotExists:如果文件所在目录不存在,则创建该目录。
数据存储与加载方法
保存数据到本地
private void SaveFriendToLocal()
{
string cacheStr = "";
// 假设 CHAT_CACHE_DIR 和 UserId 已经定义
string path = PathKit.RESROOT + string.Format(CHAT_CACHE_DIR, UserId);
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
sw.Write(cacheStr);
sw.Close();
}
该方法将 cacheStr 保存到本地文件中。首先,根据 PathKit 类获取文件路径,然后使用 FileStream 和 StreamWriter 进行文件写入操作。
从本地加载数据
private void LoadFriendFromLocal()
{
try
{
// 假设 CHAT_CACHE_DIR 和 UserId 已经定义
string path = PathKit.RESROOT + string.Format(CHAT_CACHE_DIR, UserId);
if (!System.IO.File.Exists(path))
{
return;
}
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
fs.Close();
mCacheFriend = new System.Collections.Generic.List<string>();
string[] arr = System.Text.Encoding.UTF8.GetString(bytes).Split('\n');
for (int i = 0; i < arr.Length; i++)
{
string[] item = arr[i].Split('\t');
mCacheFriend.Add(item[0]);
}
}
catch (System.Exception e)
{
UnityEngine.Debug.Log(e.Message);
}
}
该方法从本地文件中加载数据。首先,检查文件是否存在,如果存在则使用 FileStream 读取文件内容,将其转换为字符串并按行分割,最后将每行数据按制表符分割并添加到 mCacheFriend 列表中。
通过以上代码和方法,我们可以在 Unity 中实现本地数据的存储和加载,并且可以处理不同平台下的文件路径问题。