Unity之EditorUtility.SaveFilePanel-十一-

本文介绍如何在Unity编辑器中使用脚本将选中的图片保存为PNG格式,并处理不同纹理格式以确保兼容性。通过创建一个简单的Editor脚本,实现自动提示用户选择纹理,然后保存为PNG文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Unity编辑器之导入导出获取路径对话框



选中一个图片,点击 “Save Texture to file”按钮




在Editor文件夹下创建脚本
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;

public class TestEditor : EditorWindow
{
    [MenuItem("Examples/Save Texture to file")]
    static void Apply()
    {

        Texture2D texture = Selection.activeObject as Texture2D; //选中一个图片
        if (texture == null)
        {  //如果没选图片,显示提示对话框
            EditorUtility.DisplayDialog(
                "Select Texture",
                "You Must Select a Texture first!",
                "Ok");
            return;
        }
        //获取路径
        string path = EditorUtility.SaveFilePanel(
                "Save texture as PNG",
                "",
                texture.name + ".png",
                "png");

        if (path.Length != 0)
        {
            // Convert the texture to a format compatible with EncodeToPNG
            if (texture.format != TextureFormat.ARGB32 && texture.format != TextureFormat.RGB24)
            {
                Texture2D newTexture = new Texture2D(texture.width, texture.height);
                newTexture.SetPixels(texture.GetPixels(0), 0);
                texture = newTexture;
            }
            var pngData = texture.EncodeToPNG();
            if (pngData != null)
                File.WriteAllBytes(path, pngData);
        }
    }
}













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值