Unity Android端创建图片文件

本文档描述了在Unity中实现Android设备截图并保存到本地时遇到的问题。作者发现代码在电脑上运行正常,但在Android手机上执行File.WriteAllBytes时出现UnauthorizedAccessException错误。解决方法是为应用添加外部存储写入权限。调整项目设置后,问题得到解决,允许程序成功创建和保存图片文件。

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

Unity Android端创建图片文件

公司叫我负责一个Unity的程序里头有一个功能按下截图并发送
下面是我的代码

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class CaptureShoot : MonoBehaviour
{
    Rect rect;
    public Camera screen_camera;
    public GameObject Capture;
    string scrPathName;
    void Start()
    {
        rect = new Rect(0, 0, Screen.width, Screen.height);
    }
    //改方法被button按钮调用来创建图片
    public void Testing()
    {
        StartCoroutine(ScreenClick());
    }
    IEnumerator ScreenClick()
    {
        yield return null;
        // 创建一个RenderTexture对象  
        RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机  
        Capture.SetActive(false);//隐藏按钮
        screen_camera.targetTexture = rt;
        screen_camera.Render();
        // 激活这个rt, 并从中中读取像素。  
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
        screenShot.Apply();
        Capture.SetActive(true);
        // 重置相关参数,以使用camera继续在屏幕上显示  
        screen_camera.targetTexture = null;
        RenderTexture.active = null; // JC: added to avoid errors  
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件  
        byte[] bytes = screenShot.EncodeToPNG();
        string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
        string filePath = "";
        switch (Application.platform)
        {
            case RuntimePlatform.WindowsEditor:
                filePath = Application.dataPath + "/storage/emulated/0/Camera/"; //测试路径
                break;
            case RuntimePlatform.OSXEditor:
                filePath = Application.dataPath + "/storage/emulated/0/Camera/"; //测试路径
                break;
            case RuntimePlatform.Android:
                filePath = "/storage/emulated/0/Camera/screenshot/";//内置存储路径
                break;
            
        }
        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }
        scrPathName = filePath + fileName;
        File.WriteAllBytes(scrPathName, bytes);
        string[] tempPath = { scrPathName };
        ScanFile(tempPath);
        ShareManager.Instance.Share(scrPathName);
       
        yield return null;
    }
    public static void ScanFile(string[] path)
    {
        using (AndroidJavaClass PlayerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
              AndroidJavaObject playerActivity = PlayerActivity.GetStatic<AndroidJavaObject>("currentActivity");
              using (AndroidJavaObject Conn = new AndroidJavaObject("android.media.MediaScannerConnection", playerActivity, null))
              {
                  Conn.CallStatic("scanFile", playerActivity, path, null, null);
              }
          }
     }
}

这一段代码在无论如何在电脑上永远找不到毛病,但是我放到手机上测试的时候死活创建不出来文件。
后来我慢慢测试发现是

 File.WriteAllBytes(scrPathName, bytes);

这一行代码报错 UnauthorizedAccessException
解决方法非常简单
在这里插入图片描述
Wirte permission 改为 External(SDCard)
此处的打开方法为 Edit → Project Settings → Player → Other Settings

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值