当前位置:网站首页>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();
}
}
边栏推荐
- 0-5VAC转4-20mA交流电流隔离变送器/转换模块
- PHP method of obtaining image information
- 微服務遠程Debug,Nocalhost + Rainbond微服務開發第二彈
- 6-3 find the table length of the linked table
- IP network active evaluation system -- x-vision
- 知识点滴 - PCB制造工艺流程
- Debezium系列之:支持 mysql8 的 set role 語句
- QT graphicsview graphical view usage summary with flow chart development case prototype
- Class implementation of linear stack and linear queue (another binary tree pointer version)
- Unity 动态合并网格纹理
猜你喜欢
行测-图形推理-4-字母类
Cause analysis and solution of too laggy page of [test interview questions]
Microbial health network, how to restore microbial communities
Microbial Health Network, How to restore Microbial Communities
开发那些事儿:Go加C.free释放内存,编译报错是什么原因?
How to judge whether the input content is "number"
双非大厂测试员亲述:对测试员来说,学历重要吗?
Line test - graphic reasoning -5- one stroke class
Cascade-LSTM: A Tree-Structured Neural Classifier for Detecting Misinformation Cascades-KDD2020
IP network active evaluation system -- x-vision
随机推荐
Matplotlib quick start
LeetCode707. Design linked list
LeetCode203. Remove linked list elements
Apple further entered the financial sector through the 'virtual card' security function in IOS 16
Cascade-LSTM: A Tree-Structured Neural Classifier for Detecting Misinformation Cascades-KDD2020
QT graphicsview graphical view usage summary with flow chart development case prototype
DTC社群运营怎么做?
Basic knowledge of linked list
Variables and constants
Nx10.0 installation tutorial
Software evaluation center ▏ what are the basic processes and precautions for automated testing?
行测-图形推理-2-黑白格类
CTF exercise
全面掌控!打造智慧城市建设的“领导驾驶舱”
Microbial health network, how to restore microbial communities
De la famille debezium: SET ROLE statements supportant mysql8
How pyGame rotates pictures
What is ADC sampling rate (Hz) and how to calculate it
微服务架构开源框架详情介绍
0-5VAC转4-20mA交流电流隔离变送器/转换模块