将shader渲染后的效果渲染到纹理中

直接贴代码:

 

using UnityEngine;
using System.Collections;
using System.IO;

public class BakeMaterial : MonoBehaviour
{
    public int Size = 2048;
    public bool DoBake = false;

    private RenderTexture ResultTexture;
    private Material ReplaceMaterial;
    private string path = "";

    private void Start()
    {
        path = Application.dataPath + "/_TEST.png";
        print (path);
    }

    void Update()
    {
        if (DoBake)
        {
            DoBake = false;
            Bake();
        }
    }

    // Use this for initialization
    public void Bake()
    {
        if (ResultTexture == null)
        {
            ResultTexture = new RenderTexture(Size, Size, 0);
            ResultTexture.name = "Baked Texture";
        }

        bakeTexture();

        if (ReplaceMaterial != null)
        {
            GetComponent<Renderer>().material = ReplaceMaterial;
            ReplaceMaterial.mainTexture = ResultTexture;
        }
    }

    void bakeTexture()
    {
        var renderer = GetComponent<Renderer>();
        var material = Instantiate(renderer.material);
        Graphics.Blit(material.mainTexture, ResultTexture, material);
        
        Texture2D frame = new Texture2D(ResultTexture.width, ResultTexture.height);
        frame.ReadPixels(new Rect(0, 0, ResultTexture.width, ResultTexture.height), 0, 0, false);
        frame.Apply();
        byte[] bytes = frame.EncodeToPNG();
        FileStream file = File.Open(path, FileMode.Create);
        BinaryWriter binary = new BinaryWriter(file);
        binary.Write(bytes);
        file.Close();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值