返回首页DA系统C#IDE文件同步服务屏保 今天是: 2026-05-05    "立夏"  夏季的第一个节气,表示盛夏时节的正式开始

搜索
热搜: linux 技术
Hi~登录注册
查看: 1810|回复: 0

[转载] 【转载】unity 在安卓平台上读写

[复制链接]
发表于 2023-5-23 12:17:27 | 显示全部楼层 |阅读模式

少侠不来段修仙之旅吗~

您需要 登录 才可以下载或查看,没有帐号?注册成为修仙之旅的少年~

x
unity 在安卓平台上读写



   在安卓读写文件,在查阅多数资料时,发现具体指出的并没有多少,然后又是第一次尝试写博客,写的不好,可以多多交流。直接上代码;可以直接打包测试。使用的是Newtonsoft序列化与反序列化。

using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using System;


[Serializable]
public class Person
{
    public  string name { get; set; }
    public int score { get; set; }
    public Person()
    {

    }
    public Person (string name ,int score)
    {
        this.name = name;
        this.score = score;
    }  
}


public class AndroidReadOrWrite : MonoBehaviour
{
    //路径
    string path;

    private List<Person> personList;

    //总分
    int scoreA = 100;

    private void Awake()
    {
       //判断安卓路径Application.persistentDataPath该路径下 有没有我们需要的json文件,如果没有则创建
        path = Application.persistentDataPath + "/save.txt";
        if (!File.Exists(path))
        {
            File.Create(path);
            Debug.Log("创建文件");
        }
    }


    //存储数据
    public void OnButtonClick()
    {
        scoreA -= 10;
        AddData(new Person("小明", scoreA));
        Debug.Log("scoreA=" + scoreA);
    }

    //读取数据
    public void OnOpenButtonClick()
    {
        for (int i = 0; i < personList.Count; i++)
        {
            Debug.Log(personList.name + "这次考了" + personList.score);
        }
    }
    private void Start()
    {

        var content = File.ReadAllText(path);
        if (string.IsNullOrEmpty(content)) personList = new List<Person>();
        //反序列化得到我们需要的
        else personList = JsonConvert.DeserializeObject<List<Person>>(content);      
    }
    //写入数据
    public void AddData(Person person)
    {
        personList.Add(person);
        //对象序列化为 json 字符串
        File.WriteAllText(path, JsonConvert.SerializeObject(personList));
    }
}


游客
回复
*滑块验证:

DA论坛飞机票来了~
快速回复 返回顶部 返回列表