How do I Change Sprite Texture in GDScript?

Godot Version 4.2

I am trying to make a 2D Dungeon-Crawling RPG. My player sprite uses Characterbody2d. So far I have something like this:


@export var speed = 400

func get_input():
	var input_direction = Input.get_vector("left", "right", "up", "down")
	velocity = input_direction * speed

func change_sprite():
        #????????

func _physics_process(delta):
	get_input()
    change_sprite()
	move_and_slide()
       

I can’t find a simple way to change the texture of a sprite in godot 4.2.

This is my first post

func change_sprite():
	var texture = load('res://my_sprite.png')
	$Sprite2D.texture = texture

But if you are a new user to the engine, it’s better to start with the Getting Started part of the documentation here Introduction — Godot Engine (stable) documentation in English it will teach you how to use the editor, the concepts of Godot, and how to structure 2 small games one in 2D and another in 3D.

Returns

E 0:00:01:0642   aky.gd:11 @ change_sprite(): Node not found: "Sprite2D" (relative 
to "/root/CharacterBody2D").
  <C++ Error>    Method/function failed. Returning: nullptr
  <C++ Source>   scene/main/node.cpp:1638 @ get_node()
  <Stack Trace>  aky.gd:11 @ change_sprite()
                 aky.gd:17 @ _physics_process()

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