Acces variable in other funcion

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Dakkie15
extends Area2D
var move_speed = 200
const SCREEN_WIDTH = 180
const SCREEN_HEIGHT = 320
func _input(event):
	if not event is InputEventScreenTouch:
	if event.pressed:
		var touch_pos = event.get_position()
func _ready():

It doesn’t print at func _read(): What am i doing wrong? i need to get the result from the touch_pos.

:bust_in_silhouette: Reply From: jgodfrey

So, a few things…

First, the _ready function is fired immediately after the node is added to the scene tree. So, it’ll run before the _input even is ever processed. So, even if your code was right (which it isn’t), the variable wouldn’t be set at the time the _ready function fires.

Regarding, how to access the same variable in multiple functions… The easiest way is to make the variable “global” to the script. That way, you can access it from anywhere in the local script.

To do that, just define the variable outside of any function. Then just reference it as needed from anywhere else in the script. So, for example:

var my_global # define the variable outside of any function

func _ready():
    my_global = 10 # assign a value to the global variable

func my_func1():
  print(my_global) # prints "10"

func my_func2():
    my_global += 5 # change the value
    print(my_global) # prints 15