Can't get SetSurfaceOverrideMaterial() to work

Godot Version

4.2.2

Question

I’m trying to override one of three materials on a model from code(C#), but its not working as expected.
The following code does not appear to do anything:

StandardMaterial3D mat = new StandardMaterial3D();
mat.AlbedoTexture = t;
for(int iii = 0; iii < mesh.GetSurfaceOverrideMaterialCount(); iii++)
	mesh.SetSurfaceOverrideMaterial(iii, mat);

The next snippet, however, does work. The newly created material is applied.

StandardMaterial3D mat = new StandardMaterial3D();
mat.AlbedoTexture = t;
mesh.MaterialOverride = mat;

I would expect the two code snippets would have the same end result, one changing the overall material override, the other changing the specific overrides of each of the surfaces to the same thing. But the latter does change the materials, the former does nothing, as far as I can see.

The fist code snippet is just applying the same material to all surface override slots for testing, though. I ultimately want to apply 3 different materials to the three different surfaces.

I have double checked that mesh.GetSurfaceOverrideMaterialCount() is correctly returning the expected count (3), so its not that the loop is just not running.

If anyone can help me understand what I’m doing wrong it’d be appreciated

Ah, figured it out right after posting.

There was already a material override set, probably in the inspector so the more specific ones were being overwritten. Setting mesh.MaterialOverride to null before calling SetSurfaceOverrideMaterial fixed it

StandardMaterial3D mat = new StandardMaterial3D();
mat.AlbedoTexture = t;
mesh.MaterialOverride = null;	//set to null just to ensure there isn't an unintended global override
for(int iii = 0; iii < mesh.GetSurfaceOverrideMaterialCount(); iii++)
	mesh.SetSurfaceOverrideMaterial(iii, mat);
1 Like