This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

I would like to know how to create a variable that points to the same data as another variable, capturing its value automatically.

For example:

var a = 1
var b = mirror of a
a = 2
print(a) # 2
print(b) # 2

I know this applies to objects like Dictionary, but I would like to know about other data types.

in Engine by (695 points)

I cannot think of any data type that does this, but you could create a function that updates two variables to have the same value. Would this work for you?

To expand on this comment:

extends Node2D

var a: int = 0 setget set_a, get_a
var b: int = a setget , get_b

func set_a(value: int):
    a = value
    b = a

func get_a():
    return a

func get_b():
    return b

Just always go through the setters/getters for the variables.

I'm pretty sure stuff does not work like that in GdScript for simple data types. Because what you want to do is have a pointer to your value instead of having it saved. In C++ you it would be straight forward, on the other hand, in GdScript, all that is handled by the interpreter and you can't simply do it.
As a work around, you can create a class that holds a value, your int for example and use instances the class to access the values. This works because any instance of a class is a complex object, thus accessed by reference.

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.