首页 > 其他分享 >处理导入默认材质球

处理导入默认材质球

时间:2024-10-23 16:21:54浏览次数:1  
标签:text AppendLine metaContent 默认 SHADER 导入 PATH 材质 shaderContent

  1. 在资源导入后处理分配模型材质球地方进行替换成项目中的
  2. 需要处理以下细节
    • 在材质球还没有导入的时候是无法加载出材质球的
    • 动态创建材质球与shader,文件的guid必须固化,否则svn更新冲突可能会导致资源引用丢失

代码如下:

using System;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;

/// <summary>
/// 模型默认材质球替换
/// </summary>
public class ModelDefaultMaterialReplacer : AssetPostprocessor
{
    private const string MAT_PATH = "Assets/XCore/Material/Default_Model.mat";
    private const string SHADER_PATH = "Assets/Resources/Shader/XCore/ModeDefault.shader";
    private const string SHADER_GUID = "b527cdf8848d02349a7a0ad46b491d7e";
    private const string SHADER_FIND_PATH = "Legacy Shaders/ModeDefault";

    private Material OnAssignMaterialModel(Material material, Renderer renderer)
    {
        material = AssetDatabase.LoadAssetAtPath<Material>(MAT_PATH);

        if (material == null)
        {
            //创建shader
            bool createdShader = false;
            Shader shader = AssetDatabase.LoadAssetAtPath<Shader>(SHADER_PATH);
            if (shader == null)
            {
                shader = Shader.Find("Unlit/Color");
                createdShader = true;
                string shaderFullPath = Application.dataPath + SHADER_PATH.Substring(6);
                if (!Directory.Exists(Path.GetDirectoryName(SHADER_PATH)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(SHADER_PATH));
                }

                //生成shader内容
                StringBuilder shaderContent = new StringBuilder();
                shaderContent.AppendLine("Shader \""+ SHADER_FIND_PATH + "\"");
                shaderContent.AppendLine("{");
                shaderContent.AppendLine("    SubShader");
                shaderContent.AppendLine("    {");
                shaderContent.AppendLine("        Pass");
                shaderContent.AppendLine("        {");
                shaderContent.AppendLine("            CGPROGRAM");
                shaderContent.AppendLine("            #pragma vertex vert");
                shaderContent.AppendLine("            #pragma fragment frag");
                shaderContent.AppendLine("            float4 vert(float4 v : POSITION) : SV_POSITION");
                shaderContent.AppendLine("            {");
                shaderContent.AppendLine("                return UnityObjectToClipPos(v);");
                shaderContent.AppendLine("            }");
                shaderContent.AppendLine("            fixed4 frag() : SV_Target");
                shaderContent.AppendLine("            {");
                shaderContent.AppendLine("                return fixed4(1.0,1.0,1.0,1.0);");
                shaderContent.AppendLine("            }");
                shaderContent.AppendLine("            ENDCG");
                shaderContent.AppendLine("        }");
                shaderContent.AppendLine("    }");
                shaderContent.AppendLine("}");

                File.WriteAllText(shaderFullPath, shaderContent.ToString());

                //生成meta
                StringBuilder metaContent = new StringBuilder();
                metaContent.AppendLine("fileFormatVersion: 2");
                metaContent.AppendLine("guid: " + SHADER_GUID);
                metaContent.AppendLine("ShaderImporter:");
                metaContent.AppendLine("  externalObjects: {}");
                metaContent.AppendLine("  defaultTextures: []");
                metaContent.AppendLine("  nonModifiableTextures: []");
                metaContent.AppendLine("  userData:");
                metaContent.AppendLine("  assetBundleName:");
                metaContent.AppendLine("  assetBundleVariant:");
                File.WriteAllText(shaderFullPath + ".meta", metaContent.ToString());

                AssetDatabase.ImportAsset(SHADER_PATH);
            }

            //创建材质球
            string matFullPath = Application.dataPath + MAT_PATH.Substring(6);
            if (File.Exists(matFullPath))
            {
                File.Delete(matFullPath);
            }

            if (!Directory.Exists(Path.GetDirectoryName(matFullPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(matFullPath));
            }

            material = new Material(shader);
            AssetDatabase.CreateAsset(material, MAT_PATH);
            if(createdShader)
            {
                //替换材质球shader引用
                string text = File.ReadAllText(matFullPath);
                int startIndex = text.IndexOf("m_Shader:", StringComparison.Ordinal);
                int endIndex = text.IndexOf('\n', startIndex);
                string a = text.Substring(0, startIndex);
                string b = text.Substring(endIndex);
                text = a + "m_Shader: {fileID: 4800000, guid: " + SHADER_GUID + ", type: 3}" + b;

                startIndex = text.IndexOf("m_Name:", StringComparison.Ordinal);
                endIndex = text.IndexOf('\n', startIndex);
                a = text.Substring(0, startIndex);
                b = text.Substring(endIndex);
                text = a + "m_Name: " + Path.GetFileNameWithoutExtension(SHADER_PATH) + b;

                File.WriteAllText(matFullPath, text);

                //替换meta
                StringBuilder metaContent = new StringBuilder();
                metaContent.AppendLine("fileFormatVersion: 2");
                metaContent.AppendLine("guid: cb1bec2b350b9b34794f8f7df820020a");
                metaContent.AppendLine("NativeFormatImporter:");
                metaContent.AppendLine("  externalObjects: {}");
                metaContent.AppendLine("  mainObjectFileID: 2100000");
                metaContent.AppendLine("  userData:");
                metaContent.AppendLine("  assetBundleName:");
                metaContent.AppendLine("  assetBundleVariant:");
                File.WriteAllText(matFullPath + ".meta", metaContent.ToString());
            }
        }

        return material;
    }
}

标签:text,AppendLine,metaContent,默认,SHADER,导入,PATH,材质,shaderContent
From: https://www.cnblogs.com/comradexiao/p/18497670

相关文章

  • 怎么实现将WORD中的公式导入(或粘贴)到网页编辑中
    编辑器:百度ueditor前端:vue2,vue3,vue-cli,html5需求:复制粘贴word内容图片,word图片转存交互,导入pdf,导入PowerPoint(PPT)要求:开源,免费,技术支持用户体验:Ctrl+V快捷键操作该说不说,最近这块应该也是挻火的,今天早上又有网友加我微信私聊,说是想了解一下这块的技术和方案。实......
  • 【C++指南】类和对象(四):类的默认成员函数——全面剖析 : 拷贝构造函数
     引言拷贝构造函数是C++中一个重要的特性,它允许一个对象通过另一个已创建好的同类型对象来初始化。了解拷贝构造函数的概念、作用、特点、规则、默认行为以及如何自定义实现,对于编写健壮和高效的C++程序至关重要。 C++类和对象系列文章,可点击下方链接阅读:【C++指南......
  • go grpc默认长连接
    google.golang.org/grpcv1.66.0conn,err:=grpc.NewClient("127.0.0.1:1000",grpc.WithTransportCredentials(insecure.NewCredentials()))启动后就会看到该连接。创建grpcclient,默认指定idleTimeout是30分钟。keepalive.ClientParametersTime表示建连多久之后,无grpc数......
  • SSM导入依赖
    1需要导入的依赖`junitjunit3.8.1testorg.springframeworkspring-webmvc5.3.12org.springframeworkspring-jdbc5.2.10.RELEASEorg.springframeworkspring-test5.2.10.RELEASEorg.mybatismybatis3.5.5mysqlmysql-connector-java5.1.47org.my......
  • Springboot3学习(7、POI实现导入导出)
    Springboot3学习——POI实现导入导出(七)1、POI介绍‌ApachePOI是一种流行的API,允许程序员使用Java程序创建、修改和显示MSOffice文件。它是由ApacheSoftwareFoundation开发和分发的开源库,用于使用Java程序设计或修改MicrosoftOffice文件。它包含将用户......
  • el-table回显默认勾选-弹窗
    要使用nextTick()方法+element表格中的toggleRowSelection()方法记得在table标签中添加ref <el-table:data="list"ref="multipleTableRef"><el-table-columntype="selection"width="55"></el-table-column>......
  • oracle重启及impdb导入
    oracle重启停止Oracle服务sqlplus/assysdbashutdownimmediate;停止Oracle监听器sqlplus/assysdbalsnrctlstop;从Oracle安装用户开启sqlplus/assysdbastartupexit启动监听器$ORACLE_HOME/bin/lsnrctlstartimpdb导入创建逻辑目录sqlplus/assysdba......
  • SciTech-Mathematics-Probability+Statistics-Distribution: distributionFitter(分布
    说明distributionFitter(分布拟合器)以交互方式对导入MATLAB®工作区的数据进行概率分布拟合。您可以从22个内置概率分布集合进行选择,也可以创建您自己的自定义分布。该App在数据直方图上叠加显示拟合分布图。可用的绘图包括:PDF(概率密度函数)、CDF(累积分布......
  • 四,Java泛型、静态导入和可变参数
    Java泛型、静态导入和可变参数的详细指南在Java编程中,泛型、静态导入和可变参数是提高代码的重用性、类型安全和灵活性的重要特性。这些特性使得Java程序更加强大和易于维护。本文将详细介绍这些特性的使用方法和注意事项,并提供丰富的代码示例。泛型泛型是Java5引入的一项特性......
  • MongoDB数据备份&导入导出&同步
    mongodump&mongorestore单库备份##-o输出目录mongodump--host127.0.0.1--port27032-uxxx-pxxx--dbtest2--oplog-o./test2全库备份--oplog只能在副本集中使用,因为副本集初始化的时候生成oplog,单实例使用--oplog会报错。mongodump--host127.0.0.1--port......