直接上代码
using System.Collections;
using System.Collections.Generic;
using System.IO;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
public class Test
{
public string description;
public Test(string description)
{
this.description = description;
}
public Test()
{
}
}
public class SaveManager : MonoBehaviour
{
public TMP_InputField tMP_InputField;
public TextMeshProUGUI textMeshProUGUI;
public string path;
private Test test;
private void Awake()
{
path = "test.txt";
tMP_InputField.onEndEdit.AddListener(SaveData);
test = new Test();
}
void Start()
{
if (File.Exists(Path.Combine(Application.persistentDataPath, path)))
{
JsonUtility.FromJsonOverwrite(GetData(Path.Combine(Application.persistentDataPath, path)), test);
textMeshProUGUI.text = test.description;
}
else
{
JsonUtility.FromJsonOverwrite(GetData(Path.Combine(Application.streamingAssetsPath, path)), test);
textMeshProUGUI.text = test.description;
}
}
private void SaveData(string text)
{
if (!File.Exists(Path.Combine(Application.persistentDataPath, path)))
{
using (var st = File.CreateText(Path.Combine(Application.persistentDataPath, path)))
{
st.Write(JsonUtility.ToJson(new Test(text)));
st.Close();
}
}
else
{
File.WriteAllText(Path.Combine(Application.persistentDataPath, path), JsonUtility.ToJson(new Test(text)));
}
JsonUtility.FromJsonOverwrite(GetData(Path.Combine(Application.persistentDataPath, path)), test);
textMeshProUGUI.text = test.description;
}
private string GetData(string path)
{
var url = new System.Uri(path);
UnityWebRequest request = UnityWebRequest.Get(url);
request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError)
{
return "";
}
else
{
while (true)
{
if (request.downloadHandler.isDone)
{
return request.downloadHandler.text;
}
}
}
}
}
打包到安卓平台没有问题。