Unity踩坑——使用shader修改图片效果

        为了实现2D游戏一个需求,我需要对SpriteRenderer中的image做fill效果,因为SR的填充方式只有simple、tiled和sliced,所以考虑使用shader做修改。

        可实现fill效果的shader很多,这里不贴代码了,主要是说明后续情况。后来的问题是,尝试将image合并成单一图集合批优化,但是这时候发现shader对图片的操作偏移了。

        在网上找了很多资料,但是都没有用,只好自己通过git一个个提交去定位。经过多次定位后,发现直接用Load<Sprite>加载图片,并且必须删除图集,只有这样ui才不会受到图集的影响,从而能被shader正确渲染显示。

        等项目结束后我会抽时间出来分析一下,这也是我少有的接触shader的经验,是很值得学习的一个点。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用以下代码在 Unity使用 Shader 处理并保存图片: ```csharp using UnityEngine; public class SaveImageWithShader : MonoBehaviour { public Texture2D inputTexture; public Shader imageEffectShader; public string outputPath = "Output.png"; private void Start() { // 创建一个临时的 RenderTexture RenderTexture renderTexture = new RenderTexture(inputTexture.width, inputTexture.height, 0); Graphics.Blit(inputTexture, renderTexture); // 创建一个用于保存图片的 Texture2D Texture2D outputTexture = new Texture2D(renderTexture.width, renderTexture.height); // 创建一个用于保存结果的 RenderTexture RenderTexture outputRenderTexture = new RenderTexture(renderTexture.width, renderTexture.height, 0); // 使用 Shader 处理图片 Material imageEffectMaterial = new Material(imageEffectShader); Graphics.Blit(renderTexture, outputRenderTexture, imageEffectMaterial); // 将结果保存到 Texture2D RenderTexture.active = outputRenderTexture; outputTexture.ReadPixels(new Rect(0, 0, outputRenderTexture.width, outputRenderTexture.height), 0, 0); outputTexture.Apply(); // 将 Texture2D 保存为 PNG 文件 byte[] bytes = outputTexture.EncodeToPNG(); System.IO.File.WriteAllBytes(outputPath, bytes); // 释放资源 RenderTexture.active = null; Destroy(renderTexture); Destroy(outputRenderTexture); Destroy(outputTexture); Destroy(imageEffectMaterial); Debug.Log("Image saved to " + outputPath); } } ``` 将上述脚本附加到一个 GameObject 上,并在 Inspector 面板中指定输入的 Texture2D、要应用的 Shader 和输出路径。运行场景后,脚本会将经过 Shader 处理后的图片保存为 PNG 文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值