比如,序列化了一个数组,保存到磁盘上。
原来的路径是"D://test.bin",能跑,但是有点问题:序列化出来的文件和原项目离的太远,不好管理。
要是能保存到unity工程的文件夹里就好了。这个路径该怎么写?有现成的api吗?
Unity - Scripting API: Application.dataPath (unity3d.com)

- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- // 序列化和反序列化用到的
- using System;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
-
-
- public class Save : MonoBehaviour
- {
-
- // Start is called before the first frame update
- void Start()
- {
- // 00.文件的路径
- string filePath = Application.dataPath + "/cache"+"/test.bin"; // 建议先在Assets文件夹下手动建一个cache文件夹,不然可能会报错找不到../cache
-
- // 01.序列化
- int[] intArray1 = { 1, 2, 3, 4, 5 };
- int[] intArray2 = { 10, 20, 30, 40, 50 };
-
- // 创建一个二进制格式化器
- BinaryFormatter formatter = new BinaryFormatter();
-
- // 创建一个文件流
- using (FileStream stream = new FileStream(filePath, FileMode.Create))
- {
- // 序列化第一个数组
- formatter.Serialize(stream, intArray1);
-
- // 序列化第二个数组
- formatter.Serialize(stream, intArray2);
- }
-
-
- // // 02.反序列化
- // // 创建一个二进制格式化器
- // BinaryFormatter formatter = new BinaryFormatter();
-
- // // 创建一个文件流
- // using (FileStream stream = new FileStream(filePath, FileMode.Open))
- // {
- // // 反序列化第一个数组
- // int[] intArray1 = (int[])formatter.Deserialize(stream);
-
- // // 反序列化第二个数组
- // int[] intArray2 = (int[])formatter.Deserialize(stream);
-
- // // 打印数组内容
- // foreach (int i in intArray1)
- // {
- // Debug.Log(i);
- // }
-
- // foreach (int i in intArray2)
- // {
- // Debug.Log(i);
- // }
- // }
-
- }
-
- // Update is called once per frame
- void Update()
- {
-
- }
- }
-
-
