content

Specifying type in a Godot for loop can cause an invalid instance exception

Consider an untyped array that contains one type, for example an array lights which contains only Light3D.

If you try to iterate over every element in the list with a for loop by specifying the type, Godot will throw the error Trying to assign to invalid previously freed instance., even if you check if the light is valid.

for light: Light3D in lights:
	if is_instance_valid(light):
		light.visible = true

When you specify a type in this manner, the engine does something under the hood which causes this bug to happen. To avoid this exception, you need to specify the type later:

for light in lights:
	if is_instance_valid(light):
		var l: Light3D = light
		l.visible = true

I consider this bug a Godot crime

meta

tags: godot

created:

backlinks: Godot crimes

commit: 8005ffc4