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[i].name + "这次考了" + personList[i].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));
    }
}

后面会陆续推出一些适合新手的,一起加油!!!

链接:https://pan.baidu.com/s/1_DHSwwkO7aihZC4qPpX3kQ
提取码:zpav

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值