当前位置:网站首页>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();
}
}
边栏推荐
- Personal statement of testers from Shuangfei large factory: is education important for testers?
- 详解全志V853上的ARM A7和RISC-V E907之间的通信方式
- Microbial health network, how to restore microbial communities
- Matplotlib quick start
- Some parameters of Haikang IPC
- 消费品企业敏捷创新转型案例
- Cascade-LSTM: A Tree-Structured Neural Classifier for Detecting Misinformation Cascades-KDD2020
- 全面掌控!打造智慧城市建设的“领导驾驶舱”
- IP network active evaluation system -- x-vision
- ADC采样率(HZ)是什么怎么计算
猜你喜欢
Robot autonomous exploration series papers environment code
UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xf9 in position 56: illegal multibyte sequence
微生物健康網,如何恢複微生物群落
It's no exaggeration to say that this is the most user-friendly basic tutorial of pytest I've ever seen
Common verification rules of form components -2 (continuously updating ~)
Cause analysis and solution of too laggy page of [test interview questions]
行测-图形推理-6-相似图形类
Sword finger offer 55 - I. depth of binary tree
Understand the session, cookie and token at one time, and the interview questions are all finalized
XMIND mind mapping software sharing
随机推荐
LeetCode206. Reverse linked list [double pointer and recursion]
PCL . VTK files and Mutual conversion of PCD
Debezium series: MySQL tombstone event
行测-图形推理-7-相异图形类
Leetcode94. Middle order traversal of binary trees
消费品企业敏捷创新转型案例
Basic knowledge of linked list
Debezium series: introducing support for the final operator
线上面试,该如何更好的表现自己?这样做,提高50%通过率~
Form组件常用校验规则-2(持续更新中~)
Visual studio 2019 installation
消息队列与快递柜之间妙不可言的关系
Visual design form QT designer design gui single form program
CTF练习
Yarn开启ACL用户认证之后无法查看Yarn历史任务日志解决办法
Apple further entered the financial sector through the 'virtual card' security function in IOS 16
数据库每日一题---第22天:最后一次登录
Leetcode interview question 02.07 Linked list intersection [double pointer]
Robot autonomous exploration DSVP: code parsing
微服務遠程Debug,Nocalhost + Rainbond微服務開發第二彈