直接贴代码:
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();
}
}