Version: 2021.3
public static void BakeMesh (int meshID, bool convex);

参数

meshID 将从中烘焙碰撞数据的网格的实例 ID。
convex 指示是否烘焙凸面体几何体的标志。

描述

准备要与 MeshCollider 配合使用的网格。

This function runs Mesh baking and saves the result in the Mesh itself. When a MeshCollider referencing this Mesh is instantiated, it reuses the baked data instead of re-baking the Mesh. This is useful when you want to move the expensive baking process from the Scene load time or instantiation time to a different moment in time. BakeMesh is thread-safe, and does computations on the thread it was called from, however it is not valid to call BakeMesh on the same mesh from multiple threads at the same time as that causes undefined behaviour. You can use BakeMesh with the C# job system. Here is an example:

using UnityEngine;

public class MinimalTest : MonoBehaviour { public Mesh mesh;

private MeshCollider collider;

private void OnEnable() { // Bake this Mesh to use later. Physics.BakeMesh(mesh.GetInstanceID(), false); }

public void FixedUpdate() { // If the collider wasn't yet created - create it now. if (collider == null) { // No mesh baking will happen here because the mesh was pre-baked, making instantiation faster. collider = new GameObject().AddComponent<MeshCollider>(); collider.sharedMesh = mesh; } } }

BakeMesh 具有线程安全性,并且在调用它的线程上进行计算。可将 BakeMesh 与 C# 作业系统结合使用。 此示例说明如何在多个线程间烘焙网格,以便缩短在主线程上进行 MeshCollider 实例化的时间。

using Unity.Collections;
using Unity.Jobs;
using UnityEngine;

public struct BakeJob : IJobParallelFor { private NativeArray<int> meshIds;

public BakeJob(NativeArray<int> meshIds) { this.meshIds = meshIds; }

public void Execute(int index) { Physics.BakeMesh(meshIds[index], false); } }

public class JobifiedBaking : MonoBehaviour { public Mesh[] meshes; public int meshesPerJob = 10;

// Bake all the Meshes off of the main thread, and then instantiate on the main thread. private void OnEnable() { // You cannot access GameObjects and Components from other threads directly. // As such, you need to create a native array of instance IDs that BakeMesh will accept. NativeArray<int> meshIds = new NativeArray<int>(meshes.Length, Allocator.TempJob);

for (int i = 0; i < meshes.Length; ++i) { meshIds[i] = meshes[i].GetInstanceID(); }

// This spreads the expensive operation over all cores. var job = new BakeJob(meshIds); job.Schedule(meshIds.Length, meshesPerJob).Complete();

meshIds.Dispose();

// Now instantiate colliders on the main thread. for (int i = 0; i < meshes.Length; ++i) { new GameObject().AddComponent<MeshCollider>().sharedMesh = meshes[i]; } } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961