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

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Robotex

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?

:bust_in_silhouette: Reply From: deaton64


You can get the layer names:


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.

Robotex | 2021-06-24 15:55

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

deaton64 | 2021-06-24 16:12

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

Robotex | 2021-06-24 16:30

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:


deaton64 | 2021-06-24 21:21

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

gneurshk | 2022-01-06 22:21