Material Box

Material Box

WEB Design & Material Images

Godot - Sort group nodes by property value

Godot

GDScript to sort nodes in a group by property.


I created a function to sort nodes in a group by property using sort_custom().
In the code example, nodes are sorted by the 'life' property value assigned to nodes, in descending order.

func sort_group_by_life(group):
	var nodes = get_tree().get_nodes_in_group(group)
	nodes.sort_custom(func(a, b): 
		return a.life > b.life
	)
	return nodes


func _ready():
	var enemies = sort_group_by_life("enemies")

The following changes it to receive the property type as an argument to support multiple properties.

func sort_group_by_hp(group, property):
	var nodes = get_tree().get_nodes_in_group(group)
	nodes.sort_custom(func(a, b): 
		return a.property > b.property
	)
	return nodes


func _ready():
	var enemies = sort_group_by_nearest("enemies", "life")

Godot

TitleGodot - Sort group nodes by property value

CategoryGodot

Created

Update

AuthorYousuke.U