Function returns state instead of value

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

I want to make a mesh preview. I created a function that returns a texture for a button with TextureRect, but it returns a gdscript function state.

func render_thumbnail(_mesh, size, screen):
	var new_viewport = viewport.instance()
	new_viewport.size = screen
	var camera = new_viewport.find_node("Camera")
	camera.size = size
	if _mesh:
		var mesh = new_viewport.find_node("Mesh")

	var thumbnail =
	for a in 2: yield(get_tree(), "idle_frame")
	var image = new_viewport.get_texture().get_data()
	return thumbnail

It seems to me that this is due to yield (), but I do not know how to fix this or how to replace it…

:bust_in_silhouette: Reply From: omggomb

Yes this is because of yield.

I think the simplest way is to declare a signal for when the thumbnail render has finished and use that instead of return
All in one class:

signal thumbnail_finished(thumbnail)

func _ready():
    self.connect("thumbnail_finished", self, "_process_rendered_thumbnail")

func _render_thumbnail(_mesh, size, screen):
    # all the code in the render_thumbnail function except for the last line
    emit_signal("thumbnail_finished", thumbnail) # instead of return thumbnail

func _process_rendered_thumbnail(thumbnail):
    # This function gets called when the thumbnail has finished rendering
    # Do stuff
:bust_in_silhouette: Reply From: Mehmet0zen

##You can still keep the yield! ##

If you don’t want to change a code that you wrote just to get the right return value, or you just don’t want to use extra signals you can just use another yield when calling the function!

So in your case you can say;

var thumbnail = yield(render_thumbnail(mesh, size, screen), "completed")

important part is “completed” it will only set thumbnail to render_thumbnail when it returns an actual value!