Finite state machine demo, I need someone to explain to me one part

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

I’ve been trying to implement the demo version of FSM into my project but there is one part, that I don’t understand and it does not work without it at all. Here is the code I need help with:

for child in get_children():
		var err = child.connect("finished", self, "_change_state")
		if err:
			printerr(err)

Can someone please explain what is going on there and why is it so essential when the variable isn’t used anywhere else in the rest of the code? And before you ask. Yes, I did read the documentation for everything used here, but it didn’t help much.

:bust_in_silhouette: Reply From: kylemcclinton

Do you mean the err variable? That’s just making sure that the FSM was able to connect to the “finished” signal emitted by its children (I guess this particular implementation makes each individual state a child of the FSM).

The connect() function returns an error code to tell whether the connection was successful. The error code is an enumerated type, with 0 meaning OK, as in nothing went wrong. (See here for info on Error codes) So when nothing went wrong, the print statement will be skipped (“if err:” means the same thing as “if err !=0:”)

In case you’re asking about the purpose of connecting in the first place, you’re basically saying that every time one of the children calls emit_signal(“finished”), you want the FSM to call its function _change_state in response to that signal. Now the state can let the FSM (or anything else that connects to that signal) know that its time to change. And better yet, the state can blindly emit these signals without caring about who the receivers will be.

Thanks a lot, it didn’t work because I didn’t have all the states ready, and therefore it printed errors left and right as it was trying to find their scripts.

Brumda | 2021-03-01 10:03