0 votes

Is it possible to use enum values as dictionary keys in GDScript? I have some code that does the following to setup directional movement. However, when I try to access a value in the dictionary, I get the error "Invalid get index 'RIGHT' (on base: 'int')." Is this just not allowed? Thanks!

enum Direction {
    RIGHT,
    LEFT,
    UP,
    DOWN
}

var movementVectors = {
    Direction.RIGHT: Vector2.RIGHT,
    Direction.LEFT: Vector2.LEFT,
    Direction.UP: Vector2.UP,
    Direction.DOWN: Vector2.DOWN
}

var direction = Direction.RIGHT

# Gives me the error Invalid get index 'RIGHT' (on base: 'int').
var movementVector = movementVectors[direction]
in Engine by (18 points)

2 Answers

0 votes

This code works perfectly fine. The error says "on base: 'int'" - that's nothing to do with dictionary keys - it means you're trying to use [] on an integer variable.

Maybe you wrote movementVector[direction] (leaving off the "s")?

by (21,577 points)
0 votes

Try this syntax to use enum values as properties' names

var movementVectors = {}
movementVectors[Direction.RIGHT] = Vector2.RIGHT
movementVectors[Direction.LEFT] = Vector2.LEFT
by (122 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.