How to @export Sprite2D properly?

Godot Version

4.4

Question

This might be an easy question for you, guys, but I’m having trouble with it. How do you @export a Sprite2D properly? I created a CharacterBody2D scene called CardNumber. Inside that scene is a Sprite2D node. I then wrote in the code: @export var sprite: Sprite2D.

I then instantiated the CardNumber scene to the Main scene. What I want to do is duplicate the CardNumber, give each their respective sprite according to their number, and everyone’s happy. But dragging and dropping the PNG onto the Sprite inside the inspector does not work. How do you fix this?

Hi!

If you want to reference .png file, you want to export a variable of type Texture2D.
Sprite2D is a type of node that uses a Texture2D to draw on the screen, while Texture2D is used to represent a 2D image.

For instance:

extends Sprite2D


@export var image: Texture2D

func _ready() -> void:
	self.texture = image
2 Likes

It works! But somehow on the editor, it doesn’t show the image in the viewport in Main scene until hitting “play”.

Same for me, so I guess it’s an editor issue but it’s purely visual.
Glad it worked!

This is because by default, these scripts cannot run inside the editor unless you use the @tool keyword, see:

3 Likes

Placing the @tool atop the CardNumber script worked too. Thanks!

1 Like

Thank you everyone for all of your help!