Get player position and replace with new sprite

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

Hey all, I’m new to Godot and have been digging through forums and tutorials but can’t seem to find the correct solution. Currently I have a player scene and I have it collecting an item. When it collects the item I want it to increase the life counter and then replace the current player sprite with a new sprite. When I try to get the position of the sprite I get a null instance error so I’m not sure why the player scene cannot be detected.

As you can see below I have tried a few different methods of getting the position of the current player, that spritepos variable and just sprite.position. I have also tried making onready cars for new_sprite and sprite and then trying to use those in the function but that yields the same results.

func gainlife(lifeadd):
life += lifeadd
Signals.emit_signal("updatelife",life)
var new_sprite = preload("res://Scenes/Players/Player2.tscn").instance()
var sprite = get_node("res://Scenes/Players/Player.tscn")
var spritepos = sprite.get_position()
new_sprite.position = sprite.position
sprite.queue_free()
add_child(new_sprite)
print(life)
:bust_in_silhouette: Reply From: godot_dev_

First of all, getting a null instance error when trying to access the position of the sprite suggests that your scene tree is not configured such that the node “res://Scenes/Players/Player.tscn” exists.

get_node returns the node given a relative node path. However, you provide the file path of your scene, not the node relative path of the player instance. If “Scenes” is your root node name, and you have Players as a child of Scenes and Player (an instance of “res://Scenes/Players/Player.tscn”) as a child of Players, then get_node("Players/Player") may solve your problem if the "Scenes" node's script is calling the get_nodemethod. If this is not the case, make sure to give the correct toget_node` based on your scene tree setup (I don’t think ‘res://’ or ‘.tscn’ should be part of the node path’)

A second point, is that if all you want to do is change the player’s sprite, instead of creating a new node and deleting an old node, why not just update the player sprite’s texture with the new texture? sprite.texture = newTexture? It would be simple and more efficient.

This helped me solve it, thanks! I had to update the pathing and remove .tscn like you said. The script I was writing in was also too low down in the pathing so I had to move up one subdir to get to the correct level.

Centerblock | 2023-03-30 18:14