When instantiating, my node is no longer in group. How can I reference something in a group that's been instantiated?

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

Hello, I’m making a character select screen to choose between different characters to play. I’m then using the code below to bring that character into my level.

func _ready():
     var player_character = load(Game.PlayerSelect).instantiate()
     player_character.position = global_position
     add_child(player_character)

This is adding my character Boy, who is in the “player” group to the level. Which is working I can see it in the Remote tree while it’s running. However, it does not have the group symbol with it anymore.

Then my game is crashing because of the code below, since the node is not in the group I can no longer get the global position of it. Along with other references in my other script

@onready var player = get_tree().get_first_node_in_group("player")

func get_random_position():
    var vpr = get_viewport_rect().size * randf_range(1.1,1.4)
    var top_left = Vector2(player.global_position.x - vpr.x/2, player.global_position.y - vpr.y/2)

Is there a better way to do what I’m trying to accomplish or am I missing something? Like I said there is a lot more code that references this character. Also, the code works fine if I just drop the Boy.tscn file into my world scene.

Here is the code I’m using to get my character if it is needed.

func _on_boy_pressed():
	Game.PlayerSelect = "res://Player/Boy.tscn"
	get_tree().change_scene_to_file("res://World/World.tscn")
func _on_man_pressed():
	Game.PlayerSelect = "res://Player/Man.tscn"
	get_tree().change_scene_to_file("res://World/World.tscn")

I have also added add_to_group(“player”) in my boy script, thinking it might add it once it instanced it.

1 Like
:bust_in_silhouette: Reply From: PHILnYOface

I solved my issue, right after I posted, I had to use instantiate on _enter_tree() instead of _ready

func _enter_tree():
  var player_character = load(Game.PlayerSelect).instantiate()
  player_character.position = global_position
  add_child(player_character)
1 Like