GQ_Communicate/GQ_TongXin/Assets/Editor/ExtractMaterialsAndTextures.cs

80 lines
2.8 KiB
C#

using UnityEngine;
using UnityEditor;
public class ExtractMaterialsAndTextures : EditorWindow
{
[MenuItem("工具/提取材料和纹理")]
private static void ShowWindow()
{
EditorWindow window = GetWindow<ExtractMaterialsAndTextures>();
window.titleContent = new GUIContent("Extract Materials and Textures");
window.Show();
}
private void OnGUI()
{
if (GUILayout.Button("Extract Materials and Textures"))
{
GameObject[] selectedObjects = Selection.gameObjects;
foreach (GameObject obj in selectedObjects)
{
Renderer renderer = obj.GetComponent<Renderer>();
if (renderer != null)
{
Material[] materials = renderer.sharedMaterials;
foreach (Material mat in materials)
{
ExtractMaterialTextures(mat);
}
}
}
Debug.Log("提取完成!");
}
}
private void ExtractMaterialTextures(Material material)
{
string materialName = material.name;
for (int i = 0; i < ShaderUtil.GetPropertyCount(material.shader); i++)
{
if (ShaderUtil.GetPropertyType(material.shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
{
string propertyName = ShaderUtil.GetPropertyName(material.shader, i);
Texture texture = material.GetTexture(propertyName);
if (texture != null)
{
RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height);
Graphics.Blit(texture, renderTexture);
RenderTexture previousRenderTexture = RenderTexture.active;
RenderTexture.active = renderTexture;
Texture2D texture2D = new Texture2D(texture.width, texture.height);
texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture2D.Apply();
RenderTexture.active = previousRenderTexture;
RenderTexture.ReleaseTemporary(renderTexture);
byte[] bytes = texture2D.EncodeToPNG();
Object.DestroyImmediate(texture2D);
string textureName = $"{materialName}_{propertyName}";
string outputPath = $"Assets/Textures/{textureName}.png";
System.IO.File.WriteAllBytes(outputPath, bytes);
AssetDatabase.ImportAsset(outputPath, ImportAssetOptions.ForceUpdate);
Texture2D savedTexture = AssetDatabase.LoadAssetAtPath<Texture2D>(outputPath);
material.SetTexture(propertyName, savedTexture);
}
}
}
}
}