Creating Skeleton from script - Error: "Index p_bone = -1 is out of bounds (bones.size() = 2)"

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

Hi There!

I’m trying to create a skeleton from GDScript. Here is the full code, it creates a Mesh and a Skeleton with two PhysicalBones:

tool
extends EditorScript

func add_collision(bone: PhysicalBone):
	var collision = CollisionShape.new()
	collision.shape = SphereShape.new()
	bone.add_child(collision)
	collision.set_owner(get_scene())

func add_bone(skel: Skeleton, bone_name: String, parent_idx: int = -1):
	var bone = PhysicalBone.new()
	skel.add_child(bone)
	bone.set_owner(get_scene())
	bone.name = "PB_" + bone_name
	bone.bone_name = bone_name
	skel.add_bone(bone_name)
	if parent_idx >= 0:
		skel.set_bone_parent(skel.find_bone(bone_name), parent_idx)
	bone.set_owner(get_scene())
	add_collision(bone)
	
	print("bone count = ", skel.get_bone_count())

func _run():
	var cube = MeshInstance.new()
	cube.name = "Cubi"
	cube.mesh = CapsuleMesh.new()
	get_scene().add_child(cube)
	cube.set_owner(get_scene())
	
	var skel = Skeleton.new()
	get_scene().add_child(skel)
	skel.set_owner(get_scene())
	add_bone(skel, "bone_1")
	add_bone(skel, "bone_2", 0)	

Output:

bone count = 1
bone count = 2
- ERROR: get_physical_bone: Index p_bone = -1 is out of bounds (bones.size() = 2).
-   At: scene/3d/skeleton.cpp:652.
- ERROR: get_physical_bone: Index p_bone = -1 is out of bounds (bones.size() = 2).
-   At: scene/3d/skeleton.cpp:652.

error line: https://github.com/godotengine/godot/blob/a51e78528f20c410880b71c978f4038532d99659/scene/3d/skeleton.cpp#L652

I just started with Godot and I can’t figure out how to debug this. IE, is it possible to enable stack trace for these errors?
Any suggestion is appreciated!

:bust_in_silhouette: Reply From: Lopy

Stacktraces should be enabled.
The fact that your prints appear before your errors indicates that your code likely does not produce them directly, but by leaving your Skeleton in a corrupt state.

Have you tried your code outside of a tool script? The Editor is a bit different than a regular running environment, maybe it is unsuited for Skeletons?
It would allow to save your creation just as well.

:bust_in_silhouette: Reply From: Gyrth

I ran into the same issue in 3.2.3.
To fix this issue I just kept shuffling the functions around until the errors were gone.

physical_bone.set("bone_name", bone_name)
skeleton.add_child(physical_bone)
physical_bone.owner = self