当前位置:网站首页>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();
}
}
边栏推荐
- IP network active evaluation system -- x-vision
- 6-3 find the table length of the linked table
- 7-18 simple simulation of banking business queue
- It's no exaggeration to say that this is the most user-friendly basic tutorial of pytest I've ever seen
- Loki, the "open source star picking program", realizes the efficient management of harbor logs
- Debezium series: introducing support for the final operator
- 数据库每日一题---第22天:最后一次登录
- UWA Q & a collection
- Ren Qian code compilation error modification
- What is ADC sampling rate (Hz) and how to calculate it
猜你喜欢
Ligne - raisonnement graphique - 4 - classe de lettres
Digital transformation: five steps to promote enterprise progress
Matplotlib quick start
The author of LinkedList said he didn't use LinkedList himself
行测-图形推理-3-对称图形类
Unity与WebGL的相爱相杀
Explain in detail the communication mode between arm A7 and risc-v e907 on Quanzhi v853
Loki, the "open source star picking program", realizes the efficient management of harbor logs
XMIND mind mapping software sharing
Basic knowledge of linked list
随机推荐
线上面试,该如何更好的表现自己?这样做,提高50%通过率~
Personal statement of testers from Shuangfei large factory: is education important for testers?
聊聊 Dart 的空安全 (null safety) 特性
7-18 simple simulation of banking business queue
Digital transformation: five steps to promote enterprise progress
安踏DTC | 安踏转型,构建不只有FILA的增长飞轮
There is another problem just online... Warm
Redis官方ORM框架比RedisTemplate更优雅
LeetCode142. Circular linked list II [two pointers, two methods for judging links in the linked list and finding ring points]
双非大厂测试员亲述:对测试员来说,学历重要吗?
Debezium系列之:引入对 LATERAL 运算符的支持
Visual studio 2019 installation
Sword finger offer 27 Image of binary tree
The author of LinkedList said he didn't use LinkedList himself
详解全志V853上的ARM A7和RISC-V E907之间的通信方式
Yarn开启ACL用户认证之后无法查看Yarn历史任务日志解决办法
PCL .vtk文件与.pcd的相互转换
What does it mean to prefix a string with F?
【测试面试题】页面很卡的原因分析及解决方案
Sword finger offer 63 Maximum profit of stock