Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Godot3 change color of meshInstance

Tags:

godot

How can I change mesh color in Godot3 properly?

extends MeshInstance

# class member variables go here, for example:
# var a = 2
# var b = "textvar"
var i=0
export(Color) var new_color = Color(1, 1, 1, 1)
func _ready():
    var n = self
    var mat=n.get_mesh().surface_get_material(0)
    var mat2 = SpatialMaterial.new()
    mat2.albedo_color = Color(0.8, 0.0, 0.0)
    self.get_mesh().surface_set_material(0,mat2)
    set_process(true)
    # Called every time the node is added to the scene.
    # Initialization here
func _process(delta):
    randomize()
    var mat2 = SpatialMaterial.new()
    mat2.albedo_color = Color8(255, 0, 0)
    var i = rand_range(0.0,100.0)
    if i>50.0:
        self.get_mesh().surface_set_material(0,mat2)
        i=0
    else:
        mat2.albedo_color = Color8(0, 0, 255)
        self.get_mesh().surface_set_material(0,mat2)

I tried this simple code to change mesh color in godot3 engine. The idea might help to change the steplight color of the car for example in some game.

like image 906
Lesna Vevericka Avatar asked Oct 31 '25 13:10

Lesna Vevericka


1 Answers

You can use the material_override property of the MeshInstance and the albedo_color property of the material (SpatialMaterial), setting the color to whatever you need:

The example below changes the color of the MeshInstance to a shade of orange:

func _ready():
    var newMaterial = SpatialMaterial.new() #Make a new Spatial Material
    newMaterial.albedo_color = Color(0.92, 0.69, 0.13, 1.0) #Set color of new material
    $"MeshInstance".material_override = newMaterial #Assign new material to material overrride

First, make a new SpatialMaterial and assign it a name. Then, set the color of that material and set that material as the override material for the MashInstance. Just replace "MeshIsntance" with the name of your MeshInstance. For example, if this line is included in the script attached to the MeshInstance itself:

func _ready():
    var newMaterial = SpatialMaterial.new()
    newMaterial.albedo_color = Color(0.92, 0.69, 0.13, 1.0)
    self.material_override = newMaterial

If you want to undo the override:

self.material_override = null
like image 78
RStiltskin Avatar answered Nov 03 '25 19:11

RStiltskin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!