The game window crashes when 2nd projectile is shot

func _bow(val):
	arrow_spawn.add_child(Arrow_inst)
	var arrow = arrow_spawn.get_children()
	if !arrow.is_empty():
		for n in arrow.size():
			arrow[n].reparent(get_tree().root)
			arrow[n].add_constant_force(Vector2(Arrow_sped * dir, 0), Vector2(0,0))
			if n != 0:
				arrow_spawn.remove_child(arrow[n])

Here, arrow_spawn is a node2d in the tree, arrow_inst is an instance of the arrow scene, which is a rigidbody with a script.
I intend to create an instance of the arrow as a chile of a spawn point, and then unparent it to the root.
Everything works as intended when first arrow is shot, but godot game window crashes as soon as the second bullet is shot.

Should I make any changes to the code, or it is just a bug with godot 4.2.2 on mac?

What’s the error when it crashes and on which line does it crash?


There seem to be no errors popping up. The game window just crashes.
Even the warnings are not related to the code.
It crashes as soon as i hit the shoot button the second time

It’s not easy to debug something like that based on the number of lines you pasted. It might be something entirely different causing the crash.

What I would do is put print() statements everywhere so I can follow along with the output and go from there. Eliminate one line at a time until you find what’s making it gag and die.

Ok, so I added print statements as you suggested and found out that adding child the second time is where the error occurs. Not sure what the error means though.

Error: Invalid type in function ‘add_child’ in base ‘Marker2D’. The Object-derived class of argument 1 (previously freed) is not a subclass of the expected argument class.

Also, I’ve instantiated the arrow scene in _ready() so, Idk why this error occurs

well yes, you will need to create new one for every new arrow.
If you just use the same instantiated arrow, it will said it got freed because that arrow is gone

show how you instantiate the Arrow_inst

what you need to do is to do something like

const arrow_scene=preload("res://YourPathToArrowScene")

func _bow(val):
	var new_arrow=arrow_scene.instantiate()
	arrow_spawn.add_child(new_arrow)
	var arrow = arrow_spawn.get_children()
	if !arrow.is_empty():
		for n in arrow.size():
			arrow[n].reparent(get_tree().root)
			arrow[n].add_constant_force(Vector2(Arrow_sped * dir, 0), Vector2(0,0))
			if n != 0:
				arrow_spawn.remove_child(arrow[n])

Thanks a lot, instantiating the arrow within the function itself worked.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.