How to load texture for sprite

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

i want my scene to change the background sprite texture every stage
I used this code but nothing happens

$BG.texture("res://Sprites/BGandMisc/SpanishBG.png")
:bust_in_silhouette: Reply From: kidscancode

The texture property needs a Texture resource, not a filepath like you used. To load a file as a resource you need to use load(). This is demonstrated in the docs page about Resources.

For your example, you also need to set the property - texture is not a Sprite method:

$BG.texture = load("res://Sprites/BGandMisc/SpanishBG.png")

Note: you may want to use preload() instead. See the linked doc for details.

tried both load and preload but it doesnt work

Newby | 2018-07-26 22:01

Doesn’t work how? What error message are you getting? You’ll have to include some more information, because that code above is correct based on what you’ve shared about your project. Possible problems:

  • The node reference is incorrect - is “BG” a child of the node running the script?
  • The file path is wrong - you can drag the file from the file dock on the left into the script window to get the right path instead of typing it

kidscancode | 2018-07-27 17:32

:bust_in_silhouette: Reply From: olivier jeannel

the simplest I found :

extends Node2D

var playerImg = preload("res://images/300Zx_Rear.png")

func _draw():
  draw_texture(playerImg,Vector2(150,150),Color(1,1,1,1))