Download

How to apply a material to the static mesh of a static mesh component with Python?

I have a bunch of static mesh actors that I would like to apply a specific material to. Currently, I’m getting all of the actor components with unreal.EditorlLevelLibrary.get_all_level_actors_components(), looping through them and seeing which components are StaticMeshComponent, and if I find one, apply the material. However, according to the UE4 Python API, the StaticMeshComponent’s static_mesh is read-only. How can I accomplish what I’m looking to do? Thanks in advance.

Hi, you might wanna look at going up a level, getting the static mesh asset itself, and applying your materials to that static mesh asset instead? using: https://docs.unrealengine.com/en-US/…h.set_material

so it could just be an additional line of:

static_mesh.set_material(index of material to set, Material to set)

I didn’t test this out but plugging in just this with “static_mesh” replaced with the component’s static_mesh should work?

Edit:
tested this out and it works (in attachment), the only difference is that i applied it for every selected actor but the most important lines are those in bold:



import unreal

def get_selected_actors():
   return unreal.EditorLevelLibrary.get_selected_level_actors()

#load material to set 
testMaterial = unreal.load_asset('/Game/Assets/Environment/ArtKit/ArabCity/BrickOldSharp0108_MI.BrickOldSharp0108_MI')
#Class to find 
cls = unreal.StaticMeshComponent

for SM_Actors in get_selected_actors():
   SMComp = SM_Actors.get_component_by_class(cls)
**   SMAsset = SMComp.get_editor_property("static_mesh")
   SMAsset.set_material(0,testMaterial) **


1 Like

Thanks, man. Yeah, I did end up resorting to applying the material to the mesh assets. And it worked for this case. But I could definitely see the scenario where I want to use the same mesh on two actors and have them have different materials applied to them. Granted, I could do this at runtime via C++, but it would be more preferred to do it at setup in the editor. I just don’t get why the mesh for the component is read-only. I can mess with the material applied in the editor manually. I should be able to mess with the material applied via scripting, as well. It feels a bit inconsistent. Thanks for the reply.

Anything that is exposed to blueprints should also be exposed to python so pretty sure you can assign materials to StaticMeshComponents, I’m doing that using an Action Utility.


LogPython: print 'set_material' in dir(unreal.StaticMeshComponent)
LogPython: True