Topic was automatically imported from the old Question2Answer platform.
Asked By
System_Error
Hi all.
I’m trying to get a pair of guns to fire at the same time. Problem is, even though I have it mostly set up, I can’t figure out how to keep it from fussing about an instance already being a child of ‘root’.
player.gd
extends KinematicBody2D
const attack = preload("res://Game Scenes/playershot.tscn")
var playerAttack = attack.instance()
...
func shoot():
var shot_pos_1 = $GunOne.global_position
var shot_pos_2 = $GunTwo.global_position
# The actual shooting section \/ Needs a little help.
playerAttack.start(shot_pos_1)
get_parent().add_child(playerAttack)
playerAttack.start(shot_pos_2)
get_parent().add_child(playerAttack)
Whenever I try to get the projectiles to spawn, the Debugger says:
E 0:00:03.501 add_child: Can’t add child ‘PlayerShot’ to ‘root’, already has a parent ‘root’.
<C++ Error> Condition “p_child->data.parent” is true.
<C++ Source> scene/main/node.cpp:1176 @ add_child()
player.gd:45 @ shoot()
player.gd:16 @ _input()
You’ve only made one instance, because you call it when initializing the variable. The error is telling you you can’t put the same instance in two places and add it to the tree twice. You need to call instance()every time you make a new object:
extends KinematicBody2D
const attack = preload("res://Game Scenes/playershot.tscn")
#### Get rid of this: var playerAttack = attack.instance()
...
func shoot():
var shot_pos_1 = $GunOne.global_position
var shot_pos_2 = $GunTwo.global_position
# The actual shooting section \/ Needs a little help.
for shot_pos in [shot_pos_1, shot_pos_2]:
var playerAttack = attack.instance()
playerAttack.start(shot_pos)
get_parent().add_child(playerAttack)
Looks like I was too slow… I didn’t intend to add an additional variation to an already correct answer, however I don’t see a way to remove it now.
jgodfrey | 2020-02-01 16:35
Multiple answers are fine (especially if they’re correct).
kidscancode | 2020-02-01 16:38
Sure, though I wouldn’t have added my response if I had seen yours. I think I must have responded in a “stale” tab where your reply wasn’t yet visible. Thanks.