How to link a material to an object in editor?

Hi,

as partially showed here : https://rocket.unrealengine.com/questions/4252/how-to-setup-an-actor-for-an-in-editor-use-.html , I’m trying to create an object where I could control its material directly inside the editor properties with specific options. The idea is to automatically create an instanced material per actor to avoid to manually make them in the scene.

However, while I can successfully create the initial setup and control the material, if I reload the map I lost the reference (pointer) to the material and can’t get it to update anymore.

Header :

	//mesh + material
		UPROPERTY(BlueprintReadOnly, Category="aEXIL")
		class UMaterialInstanceDynamic* MI;
		
		TSubobjectPtr Mesh;

CPP Constructor :

	//material
	static ConstructorHelpers::FObjectFinder Mat(TEXT("MaterialInstanceConstant'/Game/res_editor/mat/inst_atmopsheric.inst_atmopsheric'"));

	MI = UMaterialInstanceDynamic::Create( Mat.Object, this );
	Mesh->SetMaterial(0, MI);

This current setup works the first time, if I reload the map, the actor get its material, but it is no longer referenced inside my “MI” (MaterialInstance) variable. Unfortunately the variable is not equal to NULL, probably pointing to the old memory location.

Then I jumped to a quick other solution : make the setup inside the TickActor. Again, this work the first time. I bring the actor inside the scene, with the default material of the editor. Then the actor tick for the first time and create the instance. Then I reload the map, and the actor stays with the default material (world grid material).

So I believe the editor keep my pointer somehow, but should be updated regarding the reload of the map. What could be the solution of this problem ? What could be the best way to reference my material properly ?

I tested this myself and it works for me (using the constructor method).

A couple things you should try:

1.)
Make sure your TSubobjectPtr variable is a uproperty

UPROPERTY()
TSubobjectPtr Mesh;

and call Components.Add(Mesh) in your constructor after you create the component

I didn’t see that you had done that in your code above.

2.)
Try and use a different material such as one that is in the engine content folder as a test to see if it is a problem with your material

It looks like the UPROPERTY() missing above my Mesh variable was the source of my problem.

Thanks ! :slight_smile: