通过Texture2D的EncodeToPNG方法将纹理转为图片形式
material.GetTexture方法通过属性名获取纹理贴图
material.SetTexture方法通过属性名设置纹理贴图
属性名可在shader代码中查看
using UnityEngine;
using System.IO;
public class TextureSaver : MonoBehaviour
{
public Material targetMaterial;
public string textureName = "_MainTex"; // 可自定义材质属性名
public void SaveMaterialTexture()
{
if (targetMaterial == null)
{
Debug.LogError("未指定目标材质球!");
return;
}
Texture mainTex = targetMaterial.GetTexture(textureName);
if (mainTex == null)
{
Debug.LogError($"材质中未找到纹理属性:{textureName}");
return;
}
if (mainTex is Texture2D)
{
SaveTexture2D(mainTex as Texture2D);
}
else if (mainTex is RenderTexture)
{
SaveRenderTexture(mainTex as RenderTexture);
}
else
{
Debug.LogError("不支持此纹理类型:" + mainTex.GetType());
}
}
void SaveTexture2D(Texture2D texture)
{
if (!texture.isReadable)
{
Debug.LogError("纹理不可读!请在导入设置中启用 Read/Write Enabled");
return;
}
byte[] bytes = texture.EncodeToPNG();
string filePath = Path.Combine(Application.persistentDataPath, "SavedTexture.png");
File.WriteAllBytes(filePath, bytes);
Debug.Log("保存成功:" + filePath);
}
void SaveRenderTexture(RenderTexture rt)
{
Texture2D tex2D = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false);
RenderTexture.active = rt;
tex2D.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
tex2D.Apply();
RenderTexture.active = null;
SaveTexture2D(tex2D);
Destroy(tex2D);
}
}