基于Unity AR Foundation的安卓AR相机拍照与图片保存问题
Unity AR Foundation 安卓AR相机截图保存到项目目录解决方案
问题分析
你当前的代码存在两个核心问题:
- 路径设置错误:
../ScreenShot/是相对程序运行进程的路径,并非Unity项目内的目标目录,导致文件夹创建位置不符合预期。 - 文件保存未关联路径:调用
File.WriteAllBytes(name, bytes)时仅传入文件名,未拼接目标路径,导致截图文件未保存到指定文件夹。
另外需要注意:安卓打包后,Unity项目的Assets目录属于应用只读资源目录,无法写入内容。如果是编辑器开发阶段要保存截图到项目内文件夹,可以按以下方法修改;如果是安卓运行时要保存截图,需要改为写入外部存储(比如手机相册路径)。
修正后的代码
using UnityEngine; using System.IO; #if UNITY_EDITOR using UnityEditor; #endif public class ARScreenShot : MonoBehaviour { public Camera arCamera; private int resWidth; private int resHeight; private string savePath; void Start() { resWidth = Screen.width; resHeight = Screen.height; // 设置为Unity项目Assets目录下的ScreenShot文件夹 savePath = Application.dataPath + "/ScreenShot/"; Debug.Log("截图保存路径:" + savePath); } public void ClickScreenShot() { // 创建目标文件夹(不存在则创建) if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } // 生成带时间戳的文件名 string fileName = System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".png"; string fullFilePath = savePath + fileName; // 渲染相机画面到RenderTexture RenderTexture rt = new RenderTexture(resWidth, resHeight, 24); arCamera.targetTexture = rt; arCamera.Render(); RenderTexture.active = rt; // 从RenderTexture读取像素到Texture2D Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false); screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0); screenShot.Apply(); // 编码为PNG并保存 byte[] bytes = screenShot.EncodeToPNG(); File.WriteAllBytes(fullFilePath, bytes); // 释放资源 arCamera.targetTexture = null; RenderTexture.active = null; Destroy(rt); Destroy(screenShot); Debug.Log("截图已保存:" + fullFilePath); #if UNITY_EDITOR // 编辑器下刷新资源数据库,让截图在Project窗口即时显示 AssetDatabase.Refresh(); #endif } }
关键修改点说明
- 路径修正:使用
Application.dataPath获取Unity项目的Assets目录绝对路径,拼接后得到Assets/ScreenShot/,确保文件夹创建在项目内。 - 文件路径拼接:保存时传入完整路径
savePath + fileName,确保文件写入目标文件夹。 - 资源释放:添加了相机目标纹理重置、RenderTexture和Texture2D的销毁,避免内存泄漏。
- 编辑器刷新:通过
AssetDatabase.Refresh()让截图文件在Unity编辑器的Project窗口中立即显示。
安卓运行时保存说明
如果需要在安卓设备运行时保存截图到可访问的位置(比如相册),可以将保存路径改为外部存储路径:
// 安卓外部存储的私有图片目录 savePath = Path.Combine(Application.persistentDataPath, "ScreenShot/"); // 或者直接保存到系统相册 savePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "ARScreenShots/");
同时需要在Unity的Player Settings中开启WRITE_EXTERNAL_STORAGE权限(在Player Settings > Android > Publishing Settings > Permissions中勾选)。
内容的提问来源于stack exchange,提问作者yuuun
相关产品推荐
相关产品推荐

