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);
}