0 votes

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.

Godot version latest version
in Engine by (27 points)
edited by

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.

Godot version latest version

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

1 Answer

+1 vote
Best answer

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.

by (298 points)
selected by

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

Thanks it worked i'm grateful

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.