Setting an assets material using an editor script

Hi @Mei,

I’ve updated the method to:

  • Search for the material asset to assign by name.
  • To get the slot by the model node name.

To use it:

  1. Select any number of model assets.
  2. Type a valid Material Name.
  3. Type a valid Mesh Instance name.

Hope it helps.

assetModelSetMaterial("Material Character", "Character Body");

function assetModelSetMaterial(materialName, meshInstanceName) {
  const type = editor.call("selector:type");

  if (type !== "asset") {
    return false;
  }

  // --- find material by name
  let materialAsset = editor.call("assets:findOne", asset => {
    return (
      asset.get("type") === "material" && asset.get("name") === materialName
    );
  });

  if (materialAsset[1] === undefined) return;
  materialAsset = materialAsset[1];

  const items = editor.call("selector:items");

  if (!items || items.length === 0) {
    return false;
  }

  items.forEach((item, index) => {
    const slotIndex = item._nodes.indexOf(meshInstanceName);

    if (slotIndex == -1) return true;

    item.set(
      "data.mapping." + slotIndex + ".material",
      materialAsset.get("id")
    );
  });

  console.log("--- Finished execution ---");
}

1 Like