using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnDataAdapter
{
//自由添加修改
//修改完成后需要删除老的文件!!!!
public enum DataType
{
ID,
//在这可以自由添加
//...
//添加的是自定义内容
Count
}
private string FileName = "";
private string FullPath = "";
private string[] dataArray = new string[(int)DataType.Count];
//
private static AnDataAdapter INSTANCE =null;
//单例模式
private AnDataAdapter()
{
//请确保,windows模式下有StreamingAssets文件夹
FileName = "data.an";
if (Application.platform == RuntimePlatform.Android)
FullPath = Application.persistentDataPath + "\\" + FileName;
else if (Application.platform == RuntimePlatform.WindowsEditor|| Application.platform == RuntimePlatform.WindowsPlayer)
FullPath = Application.streamingAssetsPath + "\\" + FileName;
}
//获取单例
public static AnDataAdapter GetInstance()
{
if(INSTANCE==null)
{
INSTANCE = new AnDataAdapter();
}
return INSTANCE;
}
public void Open()
{
//如果不存在就创建
if (!File.Exists(FullPath))
{
//创建,
File.CreateText(FullPath).Dispose();
//
for (int i = 0; i < (int)DataType.Count; i++)
dataArray[i] = "0";
//写,会清空原有数据
File.WriteAllLines(FullPath, dataArray, Encoding.UTF8);
}
else
{
dataArray = File.ReadAllLines(FullPath);
}
}
public void Save()
{
File.WriteAllLines(FullPath, dataArray, Encoding.UTF8);
}
public void SetData(DataType _type, string _data)
{
dataArray[(int)_type] = _data;
}
public string GetData(DataType _type)
{
return dataArray[(int)_type];
}
///你还可以使用Convert对string进行加密,例如
///Convert.FromBase64String();
//Convert.ToBase64String();
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Controller : MonoBehaviour
{
public Text Log;
private AnDataAdapter Data;
// Start is called before the first frame update
void Start()
{
Data = AnDataAdapter.GetInstance();
Data.Open();
Debug.Log(Data.GetData(AnDataAdapter.DataType.ID));
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
Data.SetData(AnDataAdapter.DataType.ID, "123");
Data.Save();
}
}
}
1.安卓设备要开启存储权限,AndroidManifest.xml添加
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2.window工程要有StreamingAssets文件夹