Trying to set a mesh's material with a different one in code

Godot Version

4.6.1

Question

I’m making a war strategy game, red vs blue. my units need to be blue if on side:1 and red if it’s on side 2. however, im having difficulty doing this.

The when i set the albedo color, all instances of this unit will have the same color since they share the same resource. So i tried using material.duplicate()

var m = $MeshInstance3D.get_active_material(0)

if PlayerSide == 1:
	m.albedo_color = Color(0.144, 0.532, 0.885, 1.0)
elif PlayerSide == 2: 
	m.albedo_color = Color(0.909, 0.243, 0.17, 1.0)

with material.duplicate(), the material does not get set for some reason.

var m = $MeshInstance3D.get_active_material(0).duplicate(true)

if PlayerSide == 1:
	m.albedo_color = Color(0.144, 0.532, 0.885, 1.0)
elif PlayerSide == 2: 
	m.albedo_color = Color(0.909, 0.243, 0.17, 1.0)


$MeshInstance3D.mesh.surface_set_material(0,m)

Could someone please help me with this.

You might want to try setting the material that the units use to be local to scene. You can adjust it by toggling the Local to Scene property in the Resource tab of the material. You should be able to just update the albedo color of the material without having to make a new one.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.