android unity 文件读写_Unity读取Android SDcard文件

本文介绍了在Unity中如何在Android设备上进行文件读写操作,包括添加必要的权限设置,以及使用IO方式和WWW方式加载SDCard上的图片资源。详细展示了通过FileStream和WWW类的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、添加权限

权限添加 :Player settings -- Other settings -- write permission的设置 Sdcard。这个是在Unity编辑器里打包的情况。

如果导出到studio 里面的话,可自行修改Manifest文件。

二、两种方式

IO方式 加载sdcard上的图片资源

加载的  /storage/emulated/0/ProjectName/image.jpg,

image = this.GetComponentInChildren();

Debug.Log("IO加载用时: image = this.GetComponent ========== " + image);

Debug.Log("IO加载: Application.dataPath " + Application.dataPath );

// Application.dataPath /data/app/com.putao.ptx.core-1/base.apk

Debug.Log("IO加载: Application.persistentDataPath " + Application.persistentDataPath);

// Application.persistentDataPath /storage/emulated/0/Android/data/com.putao.ptx.core/files

Debug.Log("IO加载:GameObject.Find" + GameObject.Find("Canvas/Avator").GetCo

Unity中,可以使用C#的System.IO命名空间下的类来进行文件读写操作。然而,由于安卓系统的权限限制,需要在AndroidManifest.xml文件中声明访问外部存储设备(如SD卡)的权限(READ_EXTERNAL_STORAGE和WRITE_EXTERNAL_STORAGE)。 以下是一个简单的例子,演示如何在Unity读取安卓文件夹: ```c# using System.IO; using UnityEngine; public class ReadFile : MonoBehaviour { void Start() { string path = "/sdcard/Download/myfile.txt"; // 文件路径 if (File.Exists(path)) { string contents = File.ReadAllText(path); // 读取文件内容 Debug.Log(contents); // 输出文件内容 } else { Debug.Log("File not found"); } } } ``` 在上面的示例中,我们首先声明了文件路径,然后使用File类的Exists方法检查文件是否存在。如果文件存在,我们使用File类的ReadAllText方法读取文件内容,并使用Debug.Log方法将其输出到控制台。如果文件不存在,则输出“File not found”。 如果要进行文件写入操作,可以使用File类的WriteAllText方法。以下是一个简单的例子,演示如何在Unity中写入安卓文件夹: ```c# using System.IO; using UnityEngine; public class WriteFile : MonoBehaviour { void Start() { string path = "/sdcard/Download/myfile.txt"; // 文件路径 string contents = "Hello, world!"; // 文件内容 File.WriteAllText(path, contents); // 写入文件内容 } } ``` 在上面的示例中,我们首先声明了文件路径和文件内容,然后使用File类的WriteAllText方法将文件内容写入到指定的文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值