How to use a Variable, which is in another funktion

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Nils

Hello,
i have this code:

extends KinematicBody2D
var pos = Vector2(507,306)

func _ready():
 var a = randi()%801+1
 var movement = Vector2(a,0)
	position = pos
	
	
func _physics_process(delta):
	
	movement = move_and_slide(movement)

I want to use the variable “movement” from the function “func _physics_process(delta)”. But i declared “movement” in the function “func _ready()”, so when in wanted to start it, it says: identifier “movement” is not declared in the current scope.

How can i fix this. I know i can declare it at the beginning of the class, but i want to declare “movement” in the function “func _ready()” and get it from the function “func _physics_process(delta)”.

Thanks Nils

:bust_in_silhouette: Reply From: Zylann

vars declared inside a function are local to that function.

I know i can declare it at the beginning of the class, but i want to declare “movement” in the function “func ready()” and get it from the function “func _physicsprocess(delta)”.

Not sure what the problem is… because that’s the solution, you really have to declare it outside of the function. You can still assign it in _ready.

You can do this:

extends KinematicBody2D

var pos = Vector2(507,306)
var movement

func _ready():
	var a = randi()%801+1
	movement = Vector2(a,0)
	position = pos


func _physics_process(delta):
    movement = move_and_slide(movement)
:bust_in_silhouette: Reply From: Nils

Thanks a lot :wink:
I thought something wrong

Thanks to that I was looking for.

Barnabet | 2019-12-11 05:46