Last active
June 25, 2024 04:39
-
-
Save Shilo/c70c8e960c02fe4c3d953f01aa4f4a1b to your computer and use it in GitHub Desktop.
Godot 4 generic wrapper for holding any value. Allows passing a value between functions by reference instead of value (copy).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Generic wrapper for holding any value. | |
## Allows passing a value between functions by reference instead of value (copy). | |
class_name ValueHolder extends RefCounted | |
## Triggers when value is updated. Current and previous values are passed. | |
signal changed(value: Variant, last_value: Variant) | |
## Current value. Changing this value will emit changed() signal. | |
var value: Variant: | |
set(new_value): | |
if value != new_value: | |
var last_value = value | |
value = new_value | |
changed.emit(value, last_value) | |
## Constructor with initial value. | |
func _init(initial_value: Variant = null): | |
value = initial_value | |
## Overrides to_string() to return the value as a string instead of self instance. | |
func _to_string(): | |
return str(value) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
func _ready(): | |
var text := ValueHolder.new("Hello") | |
var count := ValueHolder.new(0) | |
text.changed.connect(_on_value_changed) | |
count.changed.connect(_on_value_changed) | |
add_text(text) | |
add_count(count) | |
prints("Text:", text) | |
prints("Count:", count) | |
func add_text(text: ValueHolder): | |
text.value += " world!" | |
func add_count(count: ValueHolder): | |
count.value += 1 | |
func _on_value_changed(value: Variant, last_value: Variant): | |
prints("Changed:", last_value, "->", value) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Changed: Hello -> Hello world! | |
Changed: 0 -> 1 | |
Text: Hello world! | |
Count: 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment