How to change materials in a single instance?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ulises
:warning: Old Version Published before Godot 3 was released.

I have a cube in a scene, now I want to instantiate that cube several times in another scene, but I want to change the colors only some instances. I tried the following code:

const scn_square = preload("res://scenes/square.tscn")
...
func create_slab():
	for xx in range(3):
		var new_square = scn_square.instance()
		new_square.set_translation(Vector3(x, yPos, z))
		if xx == 0:
			var material = FixedMaterial.new()
			material.set_parameter(material.PARAM_DIFFUSE, Color(0, 0, 0, 1))
			new_square.get_node("mesh").get_mesh().surface_set_material(surface, material)
		add_child(new_square)

but only managed to change the color of all instances.

:bust_in_silhouette: Reply From: Zylann

That’s because you set the material on the mesh resource, not the mesh instance node.
Try this instead:

new_square.get_node("mesh").set_material_override(material)

Thanks Zylann, your suggestion works!!!, but only for the whole geometry, and seeing the documentation GeometryInstance I do not have many options. I use geometry that has more than two materials. Could you please tell me how to put the materials in my mesh instance node?
I suppose that by code it? because I do not see a node called material to add to mesh node.

ulises | 2016-08-25 15:05

AFAIK there is no override for a single surface, so you could clone the mesh resource inside the MeshInstance before modifying it. I don’t like this solution though, because it increases memory usage…

Zylann | 2016-08-25 17:18

Thanks again, I hope not consume much memory, if I find another solution will comment on here.

ulises | 2016-08-25 17:25