How do I make `@export_flags` annotation more re-usable?

Godot Version

4.4.1

Question

I’m trying to use @export_flags in my GDScript code, but am finding it a bit inconvenient. For context, I am making a turn-based RPG with characters that have various abilities. I would like to tag those abilities with flags, like “melee”, “ranged”, “support”, etc. So, I created a bit-flag based enum:

enum AbilityTags {
	NONE = 0,
	MELEE = 1 << 0,
	RANGED = 1 << 1,
	DAMAGE = 1 << 2,
	SUPPORT = 1 << 3,
}

Then, in the script for my ability node, I export the tags like so:

@export_flags("Melee", "Ranged", "Damage", "Support") var ability_tags: int = 0

There is one big problem with this approach: every time I add a new tag, I have to remember to update the export annotation as well. This becomes especially problematic if I want to export the bit-flag enum in multiple scripts. For example, I want to make a passive skill that only triggers when a character uses an ability with specific tags. The code for that passive skill would also need to export the AbilityTags enum with @export_flags.

Is there a better approach to handling this situation? Can the @export_flags annotation be written in such a way that I do not have to list every single enum option manually? Or, can this be handled better with something other than bit-flag based enum?

1 Like

You can make the script a @tool script and implement the Object._validate_property() function like:

@tool
extends Node


enum AbilityTags {
	NONE = 0,
	MELEE = 1 << 0,
	RANGED = 1 << 1,
	DAMAGE = 1 << 2,
	SUPPORT = 1 << 3,
}


@export var ability_tags:int = AbilityTags.NONE


func _validate_property(property: Dictionary) -> void:
	if property.name == "ability_tags":
		property.hint = PROPERTY_HINT_FLAGS
		property.hint_string = ",".join(AbilityTags.keys())
2 Likes

Thanks, this is exactly what I was looking for.

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