当前位置:网站首页>Unity dynamically merges mesh textures
Unity dynamically merges mesh textures
2022-07-07 23:01:00 【weixin_ forty-four million four hundred and eighty-nine thousan】
public static class CarControlMeshCombine
{
/// <summary>
/// Picture cache path , This path is not accessible at runtime , have access to StreamAssets
/// </summary>
[SerializeField]
private static string TGAPath = "Assets/ArtAssets/A_3D/Cars/LicensePlates/Textures/texture.tga";
/// <summary>
/// material Cache path , This path is not accessible at runtime , have access to StreamAssets
/// </summary>
[SerializeField]
private static string MaterialPath = "Assets/ArtAssets/A_3D/Cars/LicensePlates/Materials/mat.mat";
/// <summary>
/// Merge grids
/// </summary>
/// <param name="gameObject"></param>
public static void CombineMesh(GameObject gameObject)
{
// Get all sub objects MeshFilter/MeshRenderer
MeshFilter[] mfChildren = gameObject.GetComponentsInChildren<MeshFilter>();
MeshRenderer[] mrChildren = gameObject.GetComponentsInChildren<MeshRenderer>();
// Combined mesh
CombineInstance[] combine = new CombineInstance[mfChildren.Length];
// Create on the parent object MeshFilter and MeshRenderer
MeshRenderer mrSelf = gameObject.AddComponent<MeshRenderer>();
MeshFilter mfSelf = gameObject.AddComponent<MeshFilter>();
// Create a set of shaders and textures , And collect and save to the array
Material[] materials = new Material[mrChildren.Length];
Texture2D[] textures = new Texture2D[mrChildren.Length];
for (int i = 0; i < mrChildren.Length; i++)
{
materials[i] = mrChildren[i].sharedMaterial;
Texture2D tx = materials[i].GetTexture("_BaseMap") as Texture2D;
Texture2D tx2D = new Texture2D(tx.width, tx.height, TextureFormat.ARGB32, false);
tx2D.SetPixels(tx.GetPixels(0, 0, tx.width, tx.height));
tx2D.Apply();
textures[i] = tx2D;
}
// Get the first material , And copy the parameters , Assign to parent object
Material materialNew = new Material(materials[0].shader);
materialNew.CopyPropertiesFromMaterial(materials[0]);
mrSelf.sharedMaterial = materialNew;
// Create a texture , And assign the texture to the parent object
Texture2D texture = new Texture2D(1024, 1024);
materialNew.SetTexture("_MainTex", texture);
// Save the texture in the array in 2d In rectangular space
Rect[] rects = texture.PackTextures(textures, 10, 1024);
for (int i = 0; i < mfChildren.Length; i++)
{
if (mfChildren[i].transform == gameObject.transform)
{
continue;
}
Rect rect = rects[i];
Mesh meshCombine = mfChildren[i].mesh;
Vector2[] uvs = new Vector2[meshCombine.uv.Length];
// Put the grid uv According to the mapping rect Brush once
for (int j = 0; j < uvs.Length; j++)
{
uvs[j].x = rect.x + meshCombine.uv[j].x * rect.width;
uvs[j].y = rect.y + meshCombine.uv[j].y * rect.height;
}
meshCombine.uv = uvs;
combine[i].mesh = meshCombine;
combine[i].transform = mfChildren[i].transform.localToWorldMatrix;
mfChildren[i].gameObject.SetActive(false);
}
// Merge grids
Mesh newMesh = new Mesh();
newMesh.CombineMeshes(combine, true, true);
mfSelf.mesh = newMesh;
FileWriteTexture(texture, TGAPath);
CreateMaterial(materialNew);
LoadTextureAlter(TGAPath);
MaterialSetTexture(MaterialPath, TGAPath);
}
/// <summary>
/// Cache the merged pictures under the path
/// </summary>
/// <param name="texture"></param>
static void FileWriteTexture(Texture2D texture, string jpgPath)
{
var bytes = texture.EncodeToTGA();
FileStream file = File.Open(jpgPath, FileMode.Create);
BinaryWriter writer = new BinaryWriter(file);
writer.Write(bytes);
file.Close();
texture.Apply();
}
/// <summary>
/// The merged shaders are cached in MaterialPath Under the path , Refresh
/// </summary>
/// <param name="materialNew"></param>
static void CreateMaterial(Material materialNew)
{
AssetDatabase.CreateAsset(materialNew, MaterialPath);
AssetDatabase.Refresh();
}
/// <summary>
/// Load cache merge pictures , Modify the parameters inside
/// </summary>
static void LoadTextureAlter(string path)
{
TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
textureImporter.textureType = TextureImporterType.Default;
textureImporter.isReadable = true;
AssetDatabase.ImportAsset(path);
AssetDatabase.Refresh();
}
/// <summary>
/// The cache Material There is a phenomenon that the above map is missing , Rebind map data
/// </summary>
static void MaterialSetTexture(string materialPath, string jpgPath)
{
Material LoadMaterial = AssetDatabase.LoadAssetAtPath<Material>(materialPath);
Texture2D Loadtextur = AssetDatabase.LoadAssetAtPath<Texture2D>(jpgPath);
LoadMaterial.SetTexture("_MainTex", Loadtextur);
AssetDatabase.Refresh();
}
}
边栏推荐
- Early childhood education industry of "screwing bar": trillion market, difficult to be a giant
- 消费品企业敏捷创新转型案例
- LeetCode144. Preorder traversal of binary tree
- Unity and webgl love each other
- Leetcode206. Reverse linked list
- Unity technical notes (II) basic functions of scriptableobject
- 面试百问:如何测试App性能?
- Knowledge drop - PCB manufacturing process flow
- 数据库每日一题---第22天:最后一次登录
- 数字藏品加速出圈,MarsNFT助力多元化文旅经济!
猜你喜欢
Why is network i/o blocked?
数字化转型:五个步骤推动企业进步
行测-图形推理-5-一笔画类
行測-圖形推理-4-字母類
Line test - graphic reasoning - 1 - Chinese character class
Microbial Health Network, How to restore Microbial Communities
PHP method of obtaining image information
Microbial health network, how to restore microbial communities
0-5VAC转4-20mA交流电流隔离变送器/转换模块
CTF练习
随机推荐
How pyGame rotates pictures
Cause analysis and solution of too laggy page of [test interview questions]
Knowledge drop - PCB manufacturing process flow
How to judge whether the input content is "number"
每日一题——PAT乙级1002题
Why is network i/o blocked?
Install mxnet GPU version
Leetcode206. Reverse linked list
There is another problem just online... Warm
今日创见|企业促进创新的5大关键要素
Use JfreeChart to generate curves, histograms, pie charts, and distribution charts and display them to JSP-1
Line test - graphic reasoning -5- one stroke class
Variables and constants
数字藏品加速出圈,MarsNFT助力多元化文旅经济!
「开源摘星计划」Loki实现Harbor日志的高效管理
[environment] pycharm sets the tool to convert QRC into py file
Debezium series: support the use of variables in the Kill Command
QT graphicsview graphical view usage summary with flow chart development case prototype
Explain in detail the communication mode between arm A7 and risc-v e907 on Quanzhi v853
Line measurement - graphic reasoning -9- line problem class