0

My Player scene has a StateMachine node governing its behavior, with Idle, Move, Fall nodes as children under StateMachine. Another node, FallDownPit, listens for a signal telling it the player has wandered into a pit, and tells StateMachine to run the player's Fall state. It does this by having StateMachine and Fall as @export variables, and calling StateMachine's change_state(state: State) method with Fall as a parameter:

# fall_down_pit.gd
extends Node

@export var state_machine: StateMachine
@export var fall_state: State

func _ready() -> void:
    Global.fell_in_pit.connect(fall_down_pit)


func fall_down_pit(fall_velocity: Vector2):
    fall_state.fall_velocity = fall_velocity
    state_machine.change_state(fall_state)

I've dragged Player's StateMachine and Fall nodes into FallDownPit's export variables, but when I run the game, both state_machine and fall_state are null. If I don't assign fall_state and only assign state_machine, state_machine is populated at runtime.

Scene graph:

Player
  FallDownPit (has @export reference to both StateMachine and Fall)
  StateMachine
    Fall

Is assigning a 'nephew' node to an 'uncle' node bad practice? Am I running into some initialization order problem? Is there a better pattern to follow when trying to change states with outside signals?

3
  • I've worked around the problem by putting FallDownPit's logic into the Fall State script. I'd still appreciate knowing if the nephew/uncle connection is bad practice though. Commented Jul 26 at 21:01
  • Nodes in scene are initialized (their ready function is called) from top to bottom order. Also children of a node is initialized before the parent. For the example tree you show, order of initialization will be: FallDownPit, Fall, StateMachine, Player. If your FallDownPit uses StateMachine you should put it below StateMachine node so it initializes after StateMachine. Commented Jul 28 at 13:21
  • You can also create a separate function like "change_to_fall_state" in StateMachine, so your FallDownPit only needs a reference to StateMachine node and can call that function, getting rid of the uncle relationship. Commented Jul 28 at 13:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.