How do I access the emission energy property of a spatial material with code (so I can tween it)?

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

Hello!
I’m looking to tween some properties of my spacial material. In particular, I want to create a pulsating glow effect by tweening the emission energy value under Emission. How does one access spatial material properties in gd script? What is the syntax?

here’s what i am going with , which is clearly wrong as is not working:
(this script is attached the to mesh that has the spatial material I want to tween the properties of as its sole material):

extends MeshInstance

onready var tween = get_node("Tween")

onready var material = self.get_surface_material(0)

func _ready():
material.emission_enabled = true
tween.interpolate_property(material, "emission_energy", 0, 10, 4, Tween.TRANS_LINEAR, Tween.EASE_IN_OUT)
tween.start()

Macryc | 2020-02-12 14:53

:bust_in_silhouette: Reply From: GarlicSource

I had similar problem before, but didn’t find any direct answer.

I think there is one thing you need to pay attention to first: where did you put your material on?

In my case, my blender model has three materials on it and after importing and coverting to .tscn, you can see below in red rectangle MeshInstance → Mesh has three surfaces (Surface 1, 2, 3). I assigned my desired materials to these surfaces.

Note that in blue rectangle, MeshInstance → Material, there are also 3 slots, all empty.

Now to the tween.

In image below, the function get_surface_material_count() provided by MeshInstance gives you 3, because there are 3 materials, that’s fine. However, if you call MeshInstance function get_surface_material(), you get nothing, remember the blue rectangle above?

So the correct way is first get your Mesh object from MeshInstance object, then call function surface_get_material() of Mesh to get the material you want to use interpolate_property() on. In your case, change property emission to emission_energy and then use int value instead of Color.

Be ware of these two functions:
get_surface_material() → This is for MeshInstance
surface_get_material() → This is for Mesh

Hope this helps.