[SOLVED] function doesn't change variable

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

I’m creating a state machine and I’ve created a func:

var State = {
"Idle" : $Idle
}
var Current_State
func ready():
         test_change_state(Current_State,State,"Idle")
func physics_process(delta):
        print(Current_state)
func test_change_state(current_state,state_name,new_state):
     current_state = state_name[new_state]

if you use print(current_state.name," ",state_name, " ", new_state)

you will get

Idle {Idle:[Node:1252]} Idle

Current State in physics process prints as a null why my test change state doesn’t change the variable Current State? is there something that I’ve been missing on?

:bust_in_silhouette: Reply From: Inces

Because in test_change_state() You redefine in-function argument instead of Your Current_state variable. Capital C and You have fixed it :slight_smile:

yep, that’s true. I want to make the argument in function general because I’m going to make another state machine prior to the previous one. If I do this, then my code will work but if I try to add another state machine, I’ll have to create another function of these which makes it a hassle

Mrpaolosarino | 2021-03-28 12:52

from what I’ve heard, creating parameters inside a function will create another variable meaning, I think that’s the problem why in the physics it became null

Mrpaolosarino | 2021-03-28 12:55

Parameter created inside function never leaves this function. Yours is not even created, it is modified argument passed to this function earlier. You have to use your Current_state variable to get it out of this function, or finish function with return State_name[new_state]. What do you mean you have to create more functions for more states? I don’t see how it is necessary

Inces | 2021-03-28 13:04

The state machine above is for the player. It handles walking etc. What I will do is I will create another state machine that handles if the player picked an object or not. And to do that, I need a universal change state function, that changes both Current_state and my future hand_state. either way I think I solved the problem, thanks bro

Mrpaolosarino | 2021-03-28 13:10

:bust_in_silhouette: Reply From: Mrpaolosarino

This is for people who will find the similar problem

Functions create another variable if you create a parameter. Meaning, the function above creates another ‘current_state’ instead of directly changing the ‘Current_state’

I think this is a dumb mistake lol and here’s my solution:

func test_change_state(current_state,state_name,new_state,type):
 current_state = state_name[new_state]
if type == "Player":
    Current_state = current_state
elif type == "Items":
   Item_Current_state = current_state