当前位置:网站首页>Unity 动态合并网格纹理
Unity 动态合并网格纹理
2022-07-07 21:48:00 【weixin_44489379】
public static class CarControlMeshCombine
{
/// <summary>
/// 图片缓存路径,这个路径在运行时不可访问,可以使用StreamAssets
/// </summary>
[SerializeField]
private static string TGAPath = "Assets/ArtAssets/A_3D/Cars/LicensePlates/Textures/texture.tga";
/// <summary>
/// material缓存路径,这个路径在运行时不可访问,可以使用StreamAssets
/// </summary>
[SerializeField]
private static string MaterialPath = "Assets/ArtAssets/A_3D/Cars/LicensePlates/Materials/mat.mat";
/// <summary>
/// 合并网格
/// </summary>
/// <param name="gameObject"></param>
public static void CombineMesh(GameObject gameObject)
{
//获取所有子物体MeshFilter/MeshRenderer
MeshFilter[] mfChildren = gameObject.GetComponentsInChildren<MeshFilter>();
MeshRenderer[] mrChildren = gameObject.GetComponentsInChildren<MeshRenderer>();
//组合的网格
CombineInstance[] combine = new CombineInstance[mfChildren.Length];
//在父物体上创建MeshFilter和MeshRenderer
MeshRenderer mrSelf = gameObject.AddComponent<MeshRenderer>();
MeshFilter mfSelf = gameObject.AddComponent<MeshFilter>();
//创建一组材质球和纹理,并采集保存到数组
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;
}
//获取第一个材质,并拷贝参数,赋给父物体
Material materialNew = new Material(materials[0].shader);
materialNew.CopyPropertiesFromMaterial(materials[0]);
mrSelf.sharedMaterial = materialNew;
//创建一张纹理,并将纹理赋给父物体
Texture2D texture = new Texture2D(1024, 1024);
materialNew.SetTexture("_MainTex", texture);
//将数组中的纹理保存在2d矩形空间中
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];
//把网格的uv根据贴图的rect刷一遍
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);
}
//合并网格
Mesh newMesh = new Mesh();
newMesh.CombineMeshes(combine, true, true);
mfSelf.mesh = newMesh;
FileWriteTexture(texture, TGAPath);
CreateMaterial(materialNew);
LoadTextureAlter(TGAPath);
MaterialSetTexture(MaterialPath, TGAPath);
}
/// <summary>
/// 把合并好的图片缓存对应在路径下
/// </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>
/// 合并后的材质球缓存到MaterialPath路径下,刷新
/// </summary>
/// <param name="materialNew"></param>
static void CreateMaterial(Material materialNew)
{
AssetDatabase.CreateAsset(materialNew, MaterialPath);
AssetDatabase.Refresh();
}
/// <summary>
/// 加载缓存合并图片,修改里面的参数
/// </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>
/// 缓存的Material存在上面贴图丢失的现象,重新绑定贴图数据
/// </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();
}
}
边栏推荐
- Line test - graphic reasoning - 2 - black and white lattice class
- 面试百问:如何测试App性能?
- What is fake sharing after filling the previous hole?
- 苹果在iOS 16中通过'虚拟卡'安全功能进一步进军金融领域
- Line test - graphic reasoning - 4 - alphabetic class
- 微生物健康网,如何恢复微生物群落
- PCL .vtk文件与.pcd的相互转换
- Ligne - raisonnement graphique - 4 - classe de lettres
- 行测-图形推理-6-相似图形类
- 线上面试,该如何更好的表现自己?这样做,提高50%通过率~
猜你喜欢
Line test - graphic reasoning -7- different graphic classes
Micro service remote debug, nocalhost + rainbow micro service development second bullet
行測-圖形推理-4-字母類
C # realizes the communication between Modbus protocol and PLC
XMIND mind mapping software sharing
“拧巴”的早教行业:万亿市场,难出巨头
行测-图形推理-1-汉字类
UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xf9 in position 56: illegal multibyte sequence
新版代挂网站PHP源码+去除授权/支持燃鹅代抽
行测-图形推理-3-对称图形类
随机推荐
PHP records the pitfalls encountered in the complete docking of Tencent cloud live broadcast and im live group chat
C development - interprocess communication - named pipeline
微服务架构开源框架详情介绍
Apple further entered the financial sector through the 'virtual card' security function in IOS 16
Antd date component appears in English
Debezium series: source code reading snapshot reader
Record layoutrebuild Forcerebuildlayoutimmediate does not take effect
微生物健康網,如何恢複微生物群落
行测-图形推理-5-一笔画类
Cataloger integrates lidar and IMU for 2D mapping
Debezium系列之:引入对 LATERAL 运算符的支持
LeetCode142. Circular linked list II [two pointers, two methods for judging links in the linked list and finding ring points]
Revit secondary development - link file collision detection
C # Development -- pit encountered in JS intermodulation
0-5VAC转4-20mA交流电流隔离变送器/转换模块
This experimental syntax requires enabling the parser plugin: ‘optionalChaining‘
Line test - graphic reasoning -7- different graphic classes
Form组件常用校验规则-2(持续更新中~)
Pyqt GUI interface and logic separation
Leetcode19. Delete the penultimate node of the linked list [double pointer]