Change mesh's material color

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By LucaFox

I want to change the base color of my mesh when I press TAB.

The script:

var color1 = Color(0.3,0.3,0.3,1)

func _input(event):
if Input.is_key_pressed(KEY_TAB):
color1 = get_node(“InterfaceRoot/TabC_Colors/CP_Mesh”).get_pick_color()

The problem:

The MeshInstance’s mesh can be changed in my game. If I change mesh and then press TAB to change the color, it basically says the material no longer exists. I suppose this happens because when you change the mesh, you lose the material applied to it. Problem is, I can’t successfully create a new material, not even copy-pasting from tutorials on the web. Also, results are variable. For example, if I don’t change mesh and material I set by hand to be the default (a cube with a basic material) it works smoothly.

I’m an absolute beginner of Godot and GDScript so please try to be basic in your answer! Thanks to everyone! :slight_smile:

PLEASE NOTE: the code I pasted above misses this foundamental line:

get_node(“…”).mesh.surface_get_material(0).albedo_color = color1


LucaFox | 2019-09-07 15:50

:bust_in_silhouette: Reply From: Zylann

There are two ways you could go:

Solution 1: when you change the color, remember which color it is. Then when you change the mesh, change the color again on the new mesh.

Solution 2: use material_override instead of having the material inside your mesh. This way you can change the mesh but the override material will remain because it’s on the MeshInstance.