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)
Run Code Online (Sandbox Code Playgroud)
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.
您可以使用material_overrideMeshInstance 的属性和albedo_color材质 (SpatialMaterial) 的属性,将颜色设置为您需要的任何颜色:
下面的示例将 MeshInstance 的颜色更改为橙色:
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
Run Code Online (Sandbox Code Playgroud)
首先,创建一个新的 SpatialMaterial 并为其指定一个名称。然后,设置该材质的颜色并将该材质设置为 MashInstance 的覆盖材质。只需将“MeshIsntance”替换为您的 MeshInstance 的名称即可。例如,如果此行包含在附加到 MeshInstance 本身的脚本中:
func _ready():
var newMaterial = SpatialMaterial.new()
newMaterial.albedo_color = Color(0.92, 0.69, 0.13, 1.0)
self.material_override = newMaterial
Run Code Online (Sandbox Code Playgroud)
如果您想撤消覆盖:
self.material_override = null
Run Code Online (Sandbox Code Playgroud)