unity "EH_SampleShader/ToonShader" 把图片效果输出到 png
时间: 2023-12-27 17:03:36 浏览: 46
要将Unity中使用的“EH_SampleShader/ToonShader”效果输出为图片,你可以使用RenderTexture和Texture2D来实现。以下是一个将效果输出为PNG图片的示例代码:
```csharp
using UnityEngine;
public class RenderToonShader : MonoBehaviour
{
public Renderer quadRenderer;
public string savePath = "output.png";
private void Start()
{
// 创建RenderTexture,并设置宽高与屏幕相同
RenderTexture renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
// 设置渲染目标为renderTexture
quadRenderer.material.mainTexture = renderTexture;
// 渲染摄像机
Camera.main.targetTexture = renderTexture;
Camera.main.Render();
// 创建一张与renderTexture尺寸相同的Texture2D
Texture2D texture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGBA32, false);
// 读取像素内容到texture
RenderTexture.active = renderTexture;
texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture.Apply();
// 将texture保存为PNG图片文件
byte[] bytes = texture.EncodeToPNG();
System.IO.File.WriteAllBytes(savePath, bytes);
// 重置设置
quadRenderer.material.mainTexture = null;
Camera.main.targetTexture = null;
RenderTexture.active = null;
// 释放资源
Destroy(texture);
Destroy(renderTexture);
}
}
```
在这个示例中,我们首先创建一个与屏幕大小相同的RenderTexture,并将Quad的材质的主纹理设置为这个RenderTexture。这样,Quad上使用的“ToonShader”效果就会被渲染到这个RenderTexture上。
然后,我们创建一个与RenderTexture尺寸相同的Texture2D,并使用ReadPixels函数从RenderTexture中读取像素内容。接着,我们调用Apply函数来应用像素更改。
最后,我们使用EncodeToPNG函数将Texture2D保存为PNG格式的字节数组,并使用WriteAllBytes函数将字节数组写入文件中,保存为output.png。
请确保将Quad的Renderer组件拖放到脚本的相应变量上,并设置好保存路径savePath。当游戏运行时,Quad上的“ToonShader”效果将保存为output.png文件。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)