How to set a metadata upon instantiation/adding child? Alternatives?

Godot Version

← Godot 4 →


← Hello everybody! I am very new to Godot and I’m trying to add instances of villages into the main scene/level with different, ehrm, properties I suppose? Like setting the name and population of each village’s instance. Now, what I’m guessing is that I am supposed to use metadata to add this data to each village’s instance. However, aside from an unrelated .name feature, it seems I’m doing something wrong. Let me add the code related to this specific example (adding an instance of a “village” scene into the main scene/level and setting the name and population, both of which are metadata).

var village = preload(“res://Village.tscn”)
var newvillage = village.instantiate()
newvillage.position = Vector2(x, y) ← I set x and y to random ints = a random name
newvillage.pop = rng.randi_range(10, 50)

The last two are important. Firstly, although the .name setting seems to work fine, as it turns out, this is actually a different name setting from what I made in metadata using a string labelled “Name” with a capital N. Second is the one for pop, which is an int labelled “Pop” in metadata, and I’ve tried both with and without the capital P, neither of which have been successful so far.

Either I’m not setting metadata properly, or this is not a situation that calls for metadata at all. Unfortunately, although I’ve tried searching for more info on metadata all over the web, I’ve yielded little info, for Godot anyways. Should I set name and population by some other means, or do I set metadata in another way?

Any help that you all can give me is much appreciated!

Ideally you would use variables in your scene root script to hold those values but if you need to use metadata then you’ll need to use Object.set_meta() and Object.get_meta() to write and read the metadata.

1 Like

Thank you!

How do I manage variables of (in this case) the village instance from a script in main scene?

The same way you do it for anything else. You add a script to the root node of your village scene and set the different variables:

extends Node2D

var village_name:String
var population:int

If you are really new to Godot it’s better to start with the Getting Started part of the documentation here Introduction — Godot Engine (stable) documentation in English it will teach you how to use the editor, the concepts of Godot, and how to structure 2 small games one in 2D and another in 3D.

1 Like

What mrcdk said, and also I always recommend this 13-hour tutorial that builds a small game from start to finish:

It teaches you all of the Godot basics! Helped me a lot.