How to add a custom attribute to an (instantiated) scene/object?

Godot Version

4.2

Question

I have exhausted every search engine for this, but cannot find and answer.

So I have a very simple project with two scenes: A “main” scene and a “square” scene. In the “main” scene I spawn squares periodically.

Now, I want to assign custom data to the squares, e.g.

var square = square_scene.instantiate()
square.my_data = 7   # ← How to do that?

I have tried to attach a script to the square scene with this content:

@export var my_data = 0

But that does not make the variable available.

I am clearly missing something here, because this seems like something that should be very easily possible, like in other programming languages with classes/objects.

What do you mean by “available”? This code is fine to me.

1 Like

Indeed it works. I thought that the error “invalid index” meant that the member “my_data” cannot be found, but it turned out that the reference to the object is nil. So everything is working as expected. Thank you very much!

1 Like

You’re right, I’ve also been confused about “Invalid index”, but it just means that the variable is null (or nil when talking about a type, yes, a type for null…)

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.