Anyone know how you can create and assign a variable to a class/node dynamically in another script, something like:<br /><br />

<br />func _ready():<br />    var n = get_node("Node2D")<br />    n.new_variable = "some value"<br />

<br /><br />Which would work in Python, but GDscript doesn't like it.

Ok, there's [tt]Object.set()[/tt] and [tt]Object.get()[/tt], which looking at the docs should insert properties into a class and fetch them. Except it doesn't. After using [tt]set()[/tt] calling [tt]get()[/tt] just returns nill and printing [tt]get_property_list()[/tt] doesn't show the added property. I guess that [tt]get()[/tt] and [tt]set()[/tt] just change properties created at run time, which is not clear in the docs. [tt]set_meta()[/tt] and [tt]get_meta()[/tt] do what I'm after, but it's not as 'nice' looking as using the dotted notation (ie. some_node.my_new_prop = x). The docs particularly clear on their usage, I guess they're there for adding new properties!Basically, what I'm doing is making a journal of monsters encountered/learnt about in the game. Each monster adds a new entry, and the player can click on the icon of the monster and it'll display information about that monster. So the buttons are created dynamically, and the monster information text is stored in a dictionary in a GDscript resource. I don't want to create an individual button for each monster, and each button doesn't need it's own script. So I need a way adding the dictionary to the newly created monster icon. This way all icons can share the same code. [tt]get_meta()[/tt] and [tt]set_meta()[/tt] work, but it doesn't feel right!

You can have all the buttons call the same event handler and make them pass in their index or name so that you can have one function that will display the text for each.This can be achieved through the editor or code.  Here's the code (not tested):[code]var texts = {  'one' = 'This is one',  'two' = 'This is two',  'three' = 'This is three'}# Loop through the texts hash creating a button for # each entry.  The text of the button will be the key # and it will pass the value of the key to the even handler.for key in texts:  var b = Button.new()  add_child(b)  b.set_size(Vector2(50, 50))  b.set_pos(Vector2(100, i * 100))  b.set_text(key)  b.connect('pressed', self, 'on_journal_button_pressed', [key])func on_journal_button_pressed(key):  print(texts[key])[/code]The magic is in the connect.  The last parameter is an array of things that will be passed to the event handler.  One caveat is that you MUST have one parameter to the handler for each element in the array (in our case just one).  If there is a mismatch between the number of elements in the array and the number of parameters to the handler, the handler won't be called.  Last I checked, there wasn't any indicator of an error either, so it can be a hassle to debug.

12 days later

Thanks, I never thought to use the buttons themselves as dictionary keys.

6 years later