0

I have 5 arrays created in a function. When I call that function I pass in a "type" with the call (it's the only parameter the function accepts). I want to grab one of the arrays based on that type which is passed in.

So, for example, say I call _get_random_message('closer') I would want to get the pool_closer array from within the function.

I have it working, at present, with a match statement (and it works fine) but it's a lot of extra code I'd rather not have in there if I don't have to!

I would like do something like (and I tried this and it didn't work):

var pool_to_use = get("pool_" + str(type))

I have searched and searched to no avail so I was hoping somebody here could help me out with how to get that array based on the passed in variable.

Thanks for any/all help!

  • How exactly did `get` not work? And where is the code (an node, resource, something else)? I believe there should be another approach. – Theraot Jul 12 '21 at 16:25

1 Answers1

0

I suggest you use a dictionary. You can use the "type" as key for the dictionary, and as value the array. That would make the code shorter, and will make it easier to add more arrays. I believe you are going to need to initialize the dictionary with the arrays you want, which you can do in _init:

var _arrays:Dictionary

func _init() -> void:
    _arrays = {
        "closer": []
    }

func _get_random_message(type_name:String) -> Array:
    return _arrays.get(type_name)
Theraot
  • 31,890
  • 5
  • 57
  • 86
  • Ah this is good! I think I can adapt my code to work with this (what I need to do isn't _exactly_ this but I can alter it to fit my needs)! Thanks so much :D – JeremyPage Jul 12 '21 at 16:39