?通過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);}
}