Unity3D dynamic object optimization code sharing
- 2021-01-18 06:36:38
- OfStack
The specific explanation please look carefully in the annotation has explained very carefully, here is no more nonsense
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Dynamic object optimization
/// </summary>
public class DynamicOptimization : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
/// <summary>
/// Dynamic object optimization
/// </summary>
/// <param name="gameObject"> object </param>
public void DynamicObjectOptimization(GameObject gameObject)
{
//SkinnedMeshRenderer: Skin mesh renderer --- Gets all objects with the mesh renderer ( Contain subobjects )
SkinnedMeshRenderer[] smr = gameObject.GetComponentsInChildren<SkinnedMeshRenderer>();
//CombineInstance: The structure used to depict mesh merging , Incorporating the mesh facilitates performance optimization
List<CombineInstance> listCom = new List<CombineInstance>();
// All Material Set
List<Material> listMat = new List<Material>();
// A collection of basic information about an object
List<Transform> listTrans = new List<Transform>();
for(int i=0;i<smr.Length;i++)
{
// Get material information
listMat.AddRange(smr[i].materials);
// The object information ---bones: List of bones for skinning mesh
listTrans.AddRange(smr[i].bones);
// Get information about the shared grid
for(int k=0;k<smr[i].sharedMesh.subMeshCount;k++)
{
// Merge instance
CombineInstance ci = new CombineInstance();
// Getting grid information
ci.mesh = smr[i].sharedMesh;
// Gets the index information for the grid
ci.subMeshIndex = k;
// add
listCom.Add(ci);
}
// delete
Destroy(smr[i].gameObject);
}
// Gets renderer information on the object
SkinnedMeshRenderer smRenderer = gameObject.GetComponent<SkinnedMeshRenderer>();
// Determines whether a mesh renderer is included , If not, add it
if(smRenderer==null)
{
smRenderer = gameObject.AddComponent<SkinnedMeshRenderer>();
}
// Skin grid
smRenderer.sharedMesh = new Mesh();
// List of bone
smRenderer.bones = listTrans.ToArray();
// The material
smRenderer.materials = new Material[] { listMat[0] };
// Get information about the object
smRenderer.rootBone = gameObject.transform;
// Merged Grid ( CombineMeshes ) function 2 The parameter sets whether to merge multiple subgrids into 1 Zhang actual mesh.
//1 An actual grid can only be applied 1 So only all the meshes that have been merged are the same 1 , that is, a shared material,
// You really combine them to apply the material correctly. Otherwise, the parameter should be set to false That means you don't actually merge these sub mesh .
// They are treated as if they were combined Mesh The object's sub mesh .
smRenderer.sharedMesh.CombineMeshes(listCom.ToArray(), true);
}
}
That's all for this article. I hope you enjoy it