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 (254 points)

1 Answer

0 votes

Hi,

You can get the layer names:

print(ProjectSettings.get_setting("layer_names/2d_physics/layer_1"))

by (1,861 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():
    layer.append("")
    for i in range(1, 21):
        layer.append(ProjectSettings.get_setting("layer_names/2d_physics/layer_" + str(i)))

    print(get_layer("units"))
    print(get_layer("buildings"))
    print(get_layer("projectiles"))


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

So that will printout:

1
2
3
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 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 webmaster@godotengine.org with your username.