Node in tree VS instance of class

Godot Version

v4.3.dev5.official [89f70e98d]


Can you explain the difference between creating a node in a tree and creating an instance of class in code? Is node in the tree (with script attached) and instance of class the same?

For example, I need to work with Finite State Machine pattern and choose between:

  • place all states in one class with enum
  • create node in tree as root for FSM and children nodes for states
  • instantiate FSM and states in consumer class

The final choose depends on the hard of logic, but I am interesting what will cheaper and performance before build structures.

1 Like

An instance of a Node in code will not appear in the tree. You have to do more stuff to get it there. This shows that instances are just instances in RAM all the time.

A Node in the tree is just an instance that the Tree knows about. If you see what I mean?

You can make a state system in pure code-classes (use Refcounted or Object) and with class_name you can pretty easily refer to them all and get stuff going.

The state system in nodes is fine too. It’s a bit easier to see the sub-tree of state nodes (they can also have nice icons!) So it makes for a better visual solution for some. I made one like this.

I think nodes (in the tree) are not going to be as performative, but it’s too early to sweat that now.

One single class with all the enums and funcs to handle all the states can be fine too. Start there and then split-out as you find the need to.

Also, check out some of the neat state plugins available.