# MeshRenderer

MeshRenderer is the mesh renderer, which is the basis of all renderers, and it also comes with the ability to render static objects.

MeshRenderer is a component, so it can be created in the IDE or created using code.

# In the IDE

To create in the IDE, you only need to select a node in the scene or Prefab and add it in the Inspector:

After creating it, you can modify the parameters inside:

  1. mesh: Mesh resource, set the mesh to be rendered.
  2. lightMapScaleOffset and lightMapIndex: used for light mapping, developers generally don't need to care.
  3. castShadow: Whether to create a shadow when the camera turns on the shadow.
  4. receiveShadow: Whether to accept the shadow.
  5. materials: Set the material. When the Mesh has multiple SubMesh, you can set a material for each SubMesh.
  6. dynamicBatch: Whether to enable dynamic batching, see Batching for details.

# In the code

You can also create a MeshRenderer in the code:

const mr = entity.addComponent(engine.MeshRenderer);

After creation, all the above parameters can be set directly with mr.castShadow = true;, but there are some special general methods, and there are some places to pay attention to.

# General method

The first is material related. At runtime, developers often need to obtain a MeshRenderer Material to modify information such as Uniform. There are two completely different approaches:

// Get the material of a certain SubMesh, **will copy**!
mr.getMaterialAtIndex(index);
// equivalent to `mr.getMaterialAtIndex(0);`
mr.material

// Get the material but don't copy it.
mr.getSharedMaterialAtIndex(index);
// Equivalent to `mr.getSharedMaterialAtIndex(0);`
mr.sharedMaterial

The difference between these two methods is whether to copy or not. If the first method is used, a copy will be generated, and subsequent modifications will be made to the MeshRenderer itself; while the second method will not copy, and will not copy the obtained Material. The modification will affect all components with this original material.

Special attention should be paid here that sharedMaterial` must be used to enable GPU instantiation or batching, which is also discussed in the specific chapters.

点击咨询小助手