How to change variables inside of a paramater function

Godot Version

4.1.1

Question

Can’t increment variables in parameter functions, am I just misunderstanding how to use parameter functions?

If I use this script it prints 1, while it should print 2, or am i doing something wrong?

image

That’s right. It prints exactly the test you gave it. For the number to change, it must first be assigned.

extends Node2D

var test = 1

func _process(delta: float) -> void:
	test += 1
	print(test)
1 Like

Is it possible to change variables in parameter functions then? I’m still pretty new to coding in general, but it would be nice to know how to do that since I need it for a game I’m making atm

First of all, _ready is only used when loading a scene and will not change data as the game progresses. That’s why I took _process. Have you studied the basic documentation?

Yes, I have, I just set this piece of code up to be a test, that’s why all of the variables are called test as well. Here’s the actual code that I need help with.

image

I’m trying to make a nice sort of bobbing motion on a texture, although it didn’t really work because the tween would just play every frame in the process function. I found a workaround that would kinda work, if it wasn’t for the fact that you can’t update variables in functions. If you know how to do this another way, that’d be appreciated as well. But I kinda wanna know how to change variables in paramater functions as well, since that could kinda be important too at some point.

Apologies for asking it in this stupid way btw lol

You can read about updating variables here. This is where ScoreLabel is updated.

I’m using a translator, so I probably don’t understand exactly what you are not satisfied with and what you want to achieve. Can you post a minimal project with the problem?

Hi, you can’t alter the value of the variable in the function as you’re only passing the value of that variable and not the reference of the variable. You can pass references for arrays I think, but that doesn’t help you here.

What you can do is anything you like to the value of the variable in the function and then return that value and assign it.

This would do what you are trying to achieve:

extends Node2D

var test = 1

func _ready():
	test = increment(test)
	print(test)
	
func increment(value):
	value += 1
	return value 

The value of test is passed to your function, 1 and assigned to a new variable value. Inside the function value is incremented by 1. Then the function returns value.
By doing test = increment(test) you assign what has been returned to test and it is incremented like you want it to be.
You can do anything inside that function to alter the value of test.