One thing that became very obvious upon moving past basic game ideas was that creating instances of objects with certain parameters was not an obvious thing to do. In standard OO programming, you have a constructor and create your new object with the parameters you do or don’t specify.
In my game, I wanted to have a means of storing basic ship stats such as speed, weight etc. but finding how to do this without creating a node/script for every single ship type was putting me off using Godot.
In essence its rather easy, the Autoload demo (here) shows you how in instancing the scene.
Simply create a function to set the parameters you require in a script. In this case I wanted the player to hold the stats of their ship on their object/script.
- Create script with desired functions and data members
- Create a scene with a Node and attach the script to the node
- In the script where you want to hold the new type as a member create, a var to hold it
- In the _ready() function, load an instance of the scene containing your script and assign it to the member.
Here is another image of the Player’s script to better demonstrate:
As can be seen, the ResourceLoader loads the scene with the attached script to a local variable. This is then instanced ( using the “instance()” function) to the Player’s member “shipStats”. “setStats()” is then called to set the values of the shipStats. Finally this instance is added as a child to the player Node.
The shipStats is held as a var for convienience. This is not required. It simply means it can be retrieved without having to go through the process of calling “get_child(child number)” when needing to reference it (as there could be a lot of child nodes).
For the standard use of instancing, eg putting the Player scene in a level scene, check the official docs (reference here)