How to export a Texture variable in a tool script?

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

I have a wall node which has the following structure:

StaticBody2D
    CollisionShape2D
    Sprite

I want to export a texture variable so that I can drag different images into the walls when I’m designing my levels. I also want to see these changes in the editor.

It wouldn’t be enough to just make the children of the StaticBody2D editable so that I could drag the images into the texture field of theSprite node, because I may want to change a bunch of these nodes at once.

Here is my script:

tool
extends StaticBody2D

export(Texture) var asset setget my_func

func my_func():
	get_node("Sprite").texture = asset

This doesn’t seem to work however. When I drag an image into the asset field of my nodes, nothing happens. It doesn’t even change the text in the field from <null>.

How can I export a texture variable so that I can change the images in multiple of my nodes at once, and view these changes in the editor?

:bust_in_silhouette: Reply From: SIsilicon

The set method my_func needs one argument. That argument would be your new value.

func my_func(tex):
    asset = tex
    get_node("Sprite").texture = asset

The only issue now is that I get a null instance for “Sprite” when running the level scene, as well as a nil value. Any advice?

Diet Estus | 2018-10-12 02:57

Nevermind, this works:

tool
extends StaticBody2D

export(Texture) var asset setget my_func

func my_func(tex):
	asset = tex
	if Engine.editor_hint:
		get_node("Sprite").texture = asset

func _ready():
	get_node("Sprite").texture = asset

Diet Estus | 2018-10-12 03:02

[ export(Resource) var tex = null ] this lets you load a resource but by default the sprite will need a place holder texture.

to set the place holder texture to the sprite just call…

func _ready():
(tab)$Sprite.Texture = tex

this works for me…(after some more testing.)

Sol_Igniss | 2021-03-05 17:18

func _ready():
(tab)$Sprite.Texture = tex

Great! This is working for me too. Thank you!

juanci | 2021-03-11 18:15