Instancing a TSCN multiple times in a scene

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

I want to import players into a pitch by adding it as a child using for loop, but it keeps giving me the error: Can’t add child ‘player’ to ‘Team’, already has a parent ‘Team’.
This is the code is used below:

func Home():
    var Player_resource = load("res://Player/Player.tscn")
    var Player = Player_resource.instance()
    var player_name
    var new_array = Array()
    m_Players.resize(11)
    for x in range(m_Players.size()):
        player_name = ("player" + str(x))
	new_array.append(Player)
    for x in range(m_Players.size()):
        var append = new_array[x]
        self.add_child(append)

Thanks in advance.

Some little hints for questions. This question belongs to the category Engine not Projects.
If you post large code snippets use the CodeSample (Ctrl+K) for better readability.
Also it is a standart that variable names are lowercase. So use var player instead of var Player. Also in GDScript it is good practise to name variables in snake_case. Means if your name consists of two or more words seperate them with an underscore. So the correct name vor var Playerresource would be var player_resource.
Don’t get me wrong you don’t have to do this. But it helps to make your code understandable for other programmers which could answer your questions.

RoniPerson | 2021-01-02 10:15

Godot version latest version

“Latest version” is a moving target. Please specify your exact Godot version in the future.

Calinou | 2021-01-02 17:22

:bust_in_silhouette: Reply From: RoniPerson

You try to add the same instance of player to diffrent parents. That is not possible.
Put the

var Player = Playerresource.instance()

at the start of your for loop. So you generate a new instance of the player for every player you add.

Oh wow, thanks so much i didnt realise that. thanks once again ill check it out now

pro | 2021-01-02 09:30

Thanks it worked i’m grateful

pro | 2021-01-02 09:34

Then you may choose the answer as best answer. Then it is clear that the question is solved.

RoniPerson | 2021-01-02 10:19