0 votes

Is it possible get collision layer/mask value in code using array of layer names?

Is it possible to get layer index by it's name in code?

in Engine by (274 points)

1 Answer

0 votes


You can get the layer names:


by (2,053 points)

Looks like you are getting layer name by it's id. I need a backward procedure.

For. i.e. I have layers named "units", "buildings", "projectiles". I want to get indeces by names in code.

OK, if there's not a way of doing that, you could store all the layer names in a dictionary and look them up.

I think, I can add Autoload singleton with constants storing layer indexes and use them instead of names.

Maybe, it will be the best option

But then you'll have a list (I know it's a small list) in two places. You may not have to update it, but you might and forget about the second place.

For me, I'd do something like this:
(You can put it in a singleton and call it from anywhere etc etc)

extends Node2D
var layer = []

func _ready():
    for i in range(1, 21):
        layer.append(ProjectSettings.get_setting("layer_names/2d_physics/layer_" + str(i)))


func get_layer(layer_name):
    return layer.find(layer_name)

So that will printout:


Instead of appending an empty string at the beginning of layer, you could simply have get_layer( ) return the index plus 1

func get_layer(layer_name):
    return layer.find(layer_name) + 1
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.