Unity3D学习——截图并保存任意目录

1.前提条件:仅限于--Pc and Mac Standalone

2.准备工作:①找到System.Windows.Forms.dll:在unity的安装目录中找到它,如E:\ProgramFiles(x86)                            \Unity\Editor\Data\Mono\lib\mono\2.0
                   ②设置.NET 2.0集:Untiy默认是.NET 2.0 Subset。在Edit->Project Settings->Player->OtherSettings中修改。

3.具体实现:①任意打开一项目,新建Plugins文件夹,将找到的System.Windows.Forms.dll复制进去
                  ②新建一脚本,并拽至任一物体上。
                  ③运行后,根据操作键进行截图并保存。

4.脚本部分:

using UnityEngine;
using System.Windows.Forms;
public class Screenshot : MonoBehaviour {
   void Update() {
        if (Input.GetKeyDown(KeyCode.Z)) {
            SaveFileDialog saveLog = new SaveFileDialog();
            saveLog.InitialDirectory = "c:\\";
            saveLog.Filter = "Image Files(*.JPG;*.BMP;*.PNG)|*.JPG;*.BMP;*.PNG|All files (*.*)|*.*";
           DialogResult result = saveLog.ShowDialog();
           if (result == DialogResult.OK) {
                string path = saveLog.FileName;
                UnityEngine.Application.CaptureScreenshot(path);
           }
       }
   }
}

5.注意事项:①代码中所有的API均可在Msdn上查阅
<font face='\"微软雅黑' style="box-sizing: border-box;" \"="">http://msdn.microsoft.com/zh-cn/library/system.windows.forms.savefiledialog.aspx
                   ② EditorUtility.SaveFilePanel也可以实现相同功能,只不过必须在编辑器下才可以。

6.关于报错:
①在编辑器运行,当出现此弹窗,确定忽略即可。发布成桌面客户端是不会有这个弹窗的。

②关于其他报错,有可能是切换到.NET 2.0 Subset的时候没有实时编译造成的。Build一个客户端后错误就会消失。

7.效果图

二:第二种Unity截图保存,如果相同文件名提示是否替换

       SaveFileDlg pth = new SaveFileDlg();
        pth.structSize   = Marshal.SizeOf(pth);
        //pth.filter       = "Image Files(*.JPG;*.BMP;*.PNG)|*.JPG;*.BMP;*.PNG|All files (*.*)|*.*";  //Win32不会出错
        pth.filter       = "Image Files(*.jpg;*.bmp;*.png)\0*.jpg;*.bmp;*.png\0\0";                   //Win64适配
        pth.file         = new string(new char[256]);
        pth.maxFile      = pth.file.Length;
        pth.fileTitle    = new string(new char[64]);
        pth.maxFileTitle = pth.fileTitle.Length;
        pth.initialDir   = Application.dataPath.Replace('/', '\\'); // 默认路径
        pth.title        = "保存截图";                                                                                                  //最后这个参数才是提示是否替换的关键
        pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008 | 0x00000002;//对应Win64的适配
        pth.defExt = "jpg"; 

        if (SaveFileDialogs.GetSaveFileName(pth))
        {
            string path = pth.file;
            ScreenCapture.CaptureScreenshot(path);
        }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alxes_七局

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值