Changing Texture2D on a scene instance, in a PackedScene

Hello guys, I am generating a PackedScene Map.tscn, containing many (~1200) instances of Tag.tscn for showing POIs.

I have a problem setting different image icon for each Tag. It works when I am changing Texture2D in Tag’s _ready() function, but I want to do that during the generating of a scene, to improve performance. I guess I should attach a texture resource to the scene…?

Here is a part where it doesn’t work in a plugin where I am generating the Map.tscn:

var tag = tag_scene.instantiate()

# Tag Icon
var tag_icon = tag.get_node("%Icon")
var tag_icon_texture: Texture2D
tag_icon_texture = load("res://assets/hud/components/s/" + tag_type + ".png")
tag_icon.texture = tag_icon_texture

tag.set_owner(map)


1 Like

You must use a @tool script to to change your scene in-editor

Actually that’s not what I want to achieve. Maybe my explanation is not clear. I need to change texture when I am generating the scene and save it with this changed texture. I don’t want to do it when scene loads.

The @tool script will generate the texture before the scene loads, it will be saved and exported in a pre-computed way. The Player does not run some sections of a @tool script when exported. Specifically this example in that doc I sent

if Engine.is_editor_hint():
	# Code to execute when in editor.
else:
	# Code to execute when in game.

Unless you mean this scene is generated at run-time, in which case any script will do.

So I finally found a solution, by using custom setter

And when the scene is packed, texture is there as well as ext_resource

# Generator script

var tag = tag_scene.instantiate()
tag.icon_texture = tag_icon_texture

# ...and code for:
# adding tag to the scene
# setting tag owner 
# and packing the scene
# Tag.gd

@export var icon_texture: Texture2D:
	set(value):
		icon_texture = value
		%Icon.texture = icon_texture # setting texture to the node

Thanks for the help.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.