### Godot ENetMultiplayerPeer Mesh Design Example Source: https://docs.godotengine.org/en/4.6/classes/class_enetmultiplayerpeer.html This comprehensive example demonstrates a mesh networking setup using ENetMultiplayerPeer, including functions to create a mesh, start a host, and connect to other hosts. It handles connection events and errors, providing a robust foundation for peer-to-peer communication. ```GDScript var enet_peer: ENetMultiplayerPeer = ENetMultiplayerPeer.new() var my_id: int var current_port: int = 5001 var free_hosting: bool = true func _ready(): multiplayer.peer_connected.connect(_peer_connected) enet_peer.create_mesh(1) multiplayer.set_multiplayer_peer(enet_peer) func _peer_connected(id): print("Peer %d connected" % id) func start_host(main_scene: MainScene): if not free_hosting: main_scene._log(str("you are already listening on port ", current_port)) return while true: current_port += 1 var enet_host = ENetConnection.new() main_scene._log(str("✓ listening on ", current_port)) enet_host.create_host_bound("*", current_port, 1) free_hosting = false if not await conne(1, enet_host, 0, main_scene): free_hosting = true return current_port func conne(peer_id: int, _enet_host: ENetConnection, counter: int = 1, main_scene: MainScene = null): while true: if _enet_host.service()[0] == _enet_host.EVENT_CONNECT: print("Adding host %d" % peer_id) printerr(enet_peer.add_mesh_peer(peer_id, _enet_host)) return 0 elif _enet_host.service()[0] == _enet_host.EVENT_ERROR: if counter == 0: main_scene._log(str("✗ cannot listen on port it's ocupied")) _enet_host.destroy() return peer_id elif not _enet_host.service()[0] == _enet_host.EVENT_NONE: _enet_host.destroy() print("Mesh peer error ", peer_id, " : ", _enet_host.service()) return peer_id elif counter > 3: print("Mesh peer error ", peer_id) _enet_host.destroy() return peer_id #print("counter ", counter, _enet_host.service()) await get_tree().create_timer(1).timeout enet_peer.poll() if counter: counter += 1 func connect_to_host(host_address: String, host_port: int = PORT): while true: print("connecting to ", host_address, ":", host_port) var enet_host = ENetConnection.new() enet_host.create_host(1) var enet_packet_peer = enet_host.connect_to_host(host_address, host_port) if not await conne(enet_packet_peer.get_instance_id(), enet_host): return host_port host_port += 1 ``` -------------------------------- ### Complete ArrayMesh Setup in Godot Source: https://docs.godotengine.org/en/4.6/tutorials/3d/procedural_geometry/arraymesh.html This full example demonstrates the complete process of setting up an ArrayMesh within a `_ready()` function. It includes initializing and resizing the surface array, declaring data arrays, and creating the mesh surface. ```GDScript extends MeshInstance3D func _ready(): var surface_array = [] surface_array.resize(Mesh.ARRAY_MAX) # PackedVector**Arrays for mesh construction. var verts = PackedVector3Array() var uvs = PackedVector2Array() var normals = PackedVector3Array() var indices = PackedInt32Array() ####################################### ## Insert code here to generate mesh ## ####################################### # Assign arrays to surface array. surface_array[Mesh.ARRAY_VERTEX] = verts surface_array[Mesh.ARRAY_TEX_UV] = uvs surface_array[Mesh.ARRAY_NORMAL] = normals surface_array[Mesh.ARRAY_INDEX] = indices # Create mesh surface from mesh array. # No blendshapes, lods, or compression used. mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, surface_array) ``` ```C# public partial class MyMeshInstance3D : MeshInstance3D { public override void _Ready() { Godot.Collections.Array surfaceArray = []; surfaceArray.Resize((int)Mesh.ArrayType.Max); // C# arrays cannot be resized or expanded, so use Lists to create geometry. List verts = []; List uvs = []; List normals = []; List indices = []; /*********************************** * Insert code here to generate mesh. * *********************************/ // Convert Lists to arrays and assign to surface array surfaceArray[(int)Mesh.ArrayType.Vertex] = verts.ToArray(); surfaceArray[(int)Mesh.ArrayType.TexUV] = uvs.ToArray(); surfaceArray[(int)Mesh.ArrayType.Normal] = normals.ToArray(); surfaceArray[(int)Mesh.ArrayType.Index] = indices.ToArray(); var arrMesh = Mesh as ArrayMesh; if (arrMesh != null) { // Create mesh surface from mesh array // No blendshapes, lods, or compression used. arrMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surfaceArray); } } } ``` -------------------------------- ### Basic GDScript `_ready` Function Source: https://docs.godotengine.org/en/4.6/engine_details/class_reference/index.html An example of a `_ready` function in GDScript, demonstrating how to get a node and print its position. ```GDScript func _ready(): var sprite = get_node("Sprite2D") print(sprite.get_pos()) ``` -------------------------------- ### void setup(action_map: OpenXRActionMap, binding_modifier: OpenXRBindingModifier) Source: https://docs.godotengine.org/en/4.6/classes/class_openxrbindingmodifiereditor.html Setup this editor for the provided `action_map` and `binding_modifier`. ```APIDOC ## setup(action_map, binding_modifier) ### Description Setup this editor for the provided `action_map` and `binding_modifier`. ### Method Signature `void setup(action_map: OpenXRActionMap, binding_modifier: OpenXRBindingModifier)` ### Parameters - **action_map** (OpenXRActionMap) - The action map to associate with this editor. - **binding_modifier** (OpenXRBindingModifier) - The binding modifier to be edited. ### Return Value - `void` - This method does not return a value. ``` -------------------------------- ### start() Source: https://docs.godotengine.org/en/4.6/classes/class_skeletonik3d.html Starts the SkeletonIK3D solver. If `one_time` is `true`, the solver will run once and then stop. ```APIDOC ## start() ### Description Starts the SkeletonIK3D solver. If `one_time` is `true`, the solver will run once and then stop. ### Signature void start(one_time: bool = false) ### Parameters - **one_time** (bool) - Optional - If `true`, the solver runs once. Defaults to `false`. ### Return Value - (void) ``` -------------------------------- ### Complete GDScript Class Example Following Style Guide Source: https://docs.godotengine.org/en/4.6/tutorials/scripting/gdscript/gdscript_styleguide.html This example demonstrates a complete GDScript class, `StateMachine`, adhering to the style guide conventions for class definition, variable declaration, method naming, and signal handling. ```GDScript class_name StateMachine extends Node ## Hierarchical State machine for the player. ## ## Initializes states and delegates engine callbacks ([method Node._physics_process], ## [method Node._unhandled_input]) to the state. signal state_changed(previous, new) @export var initial_state: Node var is_active = true: set = set_is_active @onready var _state = initial_state: set = set_state @onready var _state_name = _state.name func _init(): add_to_group("state_machine") func _enter_tree(): print("this happens before the ready method!") func _ready(): state_changed.connect(_on_state_changed) _state.enter() func _unhandled_input(event): _state.unhandled_input(event) func _physics_process(delta): _state.physics_process(delta) func transition_to(target_state_path, msg={}): if not has_node(target_state_path): return var target_state = get_node(target_state_path) assert(target_state.is_composite == false) _state.exit() self._state = target_state _state.enter(msg) Events.player_state_changed.emit(_state.name) func set_is_active(value): is_active = value set_physics_process(value) set_process_unhandled_input(value) set_block_signals(not value) func set_state(value): _state = value _state_name = _state.name func _on_state_changed(previous, new): print("state changed") state_changed.emit() class State: var foo = 0 func _init(): print("Hello!") ``` -------------------------------- ### Example Script Template Paths Source: https://docs.godotengine.org/en/4.6/tutorials/scripting/creating_script_templates.html Examples demonstrating the correct file paths for custom script templates, organized by node type and language. ```text script_templates/Node/smooth_camera.gd ``` ```text script_templates/CharacterBody3D/platformer_movement.gd ``` -------------------------------- ### Handle OpenXR Session Start in _enter_tree (GDScript) Source: https://docs.godotengine.org/en/4.6/tutorials/xr/openxr_spatial_entities.html This function connects to the OpenXR session_begun signal to set up the spatial context when the session starts. It also attempts immediate setup if the session is already running. ```GDScript func _enter_tree(): var openxr_interface : OpenXRInterface = XRServer.find_interface("OpenXR") if openxr_interface and openxr_interface.is_initialized(): # Just in case our session hasn't started yet, # call our spatial context creation on start. openxr_interface.session_begun.connect(_set_up_spatial_context) # And in case it is already up and running, call it already, # it will exit if we've called it too early. _set_up_spatial_context() ``` -------------------------------- ### Example Content for version.txt Source: https://docs.godotengine.org/en/4.6/engine_details/development/compiling/introduction_to_the_buildsystem.html The version.txt file should contain the Godot version identifier, such as 4.4.1.stable, on its first line to ensure correct installation of export templates. ```text 4.4.1.stable ``` -------------------------------- ### start(from_pos: float = 0.0) Source: https://docs.godotengine.org/en/4.6/classes/class_audiostreamplayback.html Starts the audio stream from a specified position in seconds. ```APIDOC ## start(from_pos: float = 0.0) ### Description Starts the stream from the given `from_pos`, in seconds. ### Method void start(from_pos: float = 0.0) ### Parameters - **from_pos** (float) - The position to start from, in seconds. Defaults to `0.0`. ### Returns (void) ``` -------------------------------- ### start(time_sec: float = -1) Source: https://docs.godotengine.org/en/4.6/classes/class_timer.html Starts the timer. Optionally sets the wait_time before starting. ```APIDOC ## Method: start(time_sec: float = -1) ### Description Starts the timer. If `time_sec` is a positive value, it will set the `wait_time` property to this value before starting the timer. If `time_sec` is -1 (default), the timer will use its current `wait_time`. ### Method Signature `void start(time_sec: float = -1)` ### Parameters - **time_sec** (`float`) - Optional - The time in seconds to wait before emitting the timeout signal. If -1, uses the current `wait_time`. ### Return Value `void` ``` -------------------------------- ### Error setup(server_options: TLSOptions) Source: https://docs.godotengine.org/en/4.6/classes/class_dtlsserver.html Setup the DTLS server to use the given `server_options`. See TLSOptions.server(). ```APIDOC ## setup(server_options: TLSOptions) ### Description Setup the DTLS server to use the given `server_options`. See TLSOptions.server(). ### Method Signature Error setup(server_options: TLSOptions) ### Parameters #### Method Parameters - **server_options** (TLSOptions) - Required - The TLS options to use for the server. ### Returns - **Error** - An error code indicating success or failure. ``` -------------------------------- ### Start Headless Server with DisplayServer Check (GDScript/C#) Source: https://docs.godotengine.org/en/4.6/tutorials/export/exporting_for_dedicated_servers.html This code snippet allows starting a dedicated server when the Godot binary is run with the `--headless` command-line argument. Place it in your main scene's or an autoload's `_ready()` method. ```GDScript if DisplayServer.get_name() == "headless": # Run your server startup code here... # # Using this check, you can start a dedicated server by running # a Godot binary (editor or export template) with the `--headless` # command-line argument. pass ``` ```C# using System.Linq; if (DisplayServer.GetName() == "headless") { // Run your server startup code here... // // Using this check, you can start a dedicated server by running // a Godot binary (editor or export template) with the `--headless` // command-line argument. } ``` -------------------------------- ### Run HTTPClient Example Script Source: https://docs.godotengine.org/en/4.6/tutorials/networking/http_client_class.html Execute the Godot script from the command line to run the HTTPClient demonstration. ```Shell c:\godot> godot -s http_test.gd ``` ```Shell c:\godot> godot -s HTTPTest.cs ``` -------------------------------- ### Engine.prototype.startGame(override) Source: https://docs.godotengine.org/en/4.6/tutorials/platform/web/html5_shell_classref.html Start the game instance using the given configuration override (if any). This will initialize the instance if it is not initialized and load the engine if not loaded. ```APIDOC ## INSTANCE METHOD Engine.prototype.startGame(override) ### Description Start the game instance using the given configuration override (if any). This will initialize the instance if it is not initialized. This will load the engine if it is not loaded, and preload the main pck. This method expects the initial config (or the override) to have both the `executable` and `mainPack` properties set. ### Arguments - **override** (EngineConfig()) - Optional - An optional configuration override. ### Returns Promise that resolves once the game started. ``` -------------------------------- ### Start Godot HTML5 Engine Automatically Source: https://docs.godotengine.org/en/4.6/tutorials/platform/web/customizing_html5_shell.html Use this snippet for a simple project startup. It automatically loads and initializes the engine, then starts the game using the provided configuration. The `startGame` method returns a Promise for tracking. ```javascript const engine = new Engine($GODOT_CONFIG); engine.startGame({ /* optional override configuration, eg. */ // unloadAfterInit: false, // canvasResizePolicy: 0, // ... }); ``` -------------------------------- ### Start Server with Custom Command-Line Argument (GDScript/C#) Source: https://docs.godotengine.org/en/4.6/tutorials/export/exporting_for_dedicated_servers.html Use this snippet to start a dedicated server when a custom command-line argument, such as `--server`, is provided. Integrate it into your main scene's or an autoload's `_ready()` method. ```GDScript if "--server" in OS.get_cmdline_user_args(): # Run your server startup code here... # # Using this check, you can start a dedicated server by running # a Godot binary (editor or export template) with the `--server` # command-line argument. pass ``` ```C# using System.Linq; if (OS.GetCmdlineUserArgs().Contains("--server")) { // Run your server startup code here... // // Using this check, you can start a dedicated server by running // a Godot binary (editor or export template) with the `--server` // command-line argument. } ``` -------------------------------- ### Implement a Custom MainLoop (GDScript/C#) Source: https://docs.godotengine.org/en/4.6/classes/class_mainloop.html This example demonstrates how to create a custom MainLoop by extending the base class and overriding its lifecycle methods: _initialize for setup, _process for per-frame logic (returning true to end the loop), and _finalize for cleanup. ```GDScript class_name CustomMainLoop extends MainLoop var time_elapsed = 0 func _initialize(): print("Initialized:") print(" Starting time: %s" % str(time_elapsed)) func _process(delta): time_elapsed += delta # Return true to end the main loop. return Input.get_mouse_button_mask() != 0 || Input.is_key_pressed(KEY_ESCAPE) func _finalize(): print("Finalized:") print(" End time: %s" % str(time_elapsed)) ``` ```C# using Godot; [GlobalClass] public partial class CustomMainLoop : MainLoop { private double _timeElapsed = 0; public override void _Initialize() { GD.Print("Initialized:"); GD.Print($" Starting Time: {_timeElapsed}"); } public override bool _Process(double delta) { _timeElapsed += delta; // Return true to end the main loop. return Input.GetMouseButtonMask() != 0 || Input.IsKeyPressed(Key.Escape); } private void _Finalize() { GD.Print("Finalized:"); GD.Print($" End Time: {_timeElapsed}"); } } ``` -------------------------------- ### Usage Examples Source: https://docs.godotengine.org/en/4.6/classes/class_packetpeerudp.html Examples demonstrating how to send and receive UDP packets using PacketPeerUDP. ```APIDOC var peer = PacketPeerUDP.new() # Optionally, you can select the local port used to send the packet. peer.bind(4444) peer.set_dest_address("1.1.1.1", 4433) peer.put_packet("hello".to_utf8_buffer()) ``` ```APIDOC var peer func _ready(): peer = PacketPeerUDP.new() peer.bind(4433) func _process(_delta): if peer.get_available_packet_count() > 0: var array_bytes = peer.get_packet() var packet_string = array_bytes.get_string_from_ascii() print("Received message: ", packet_string) ``` -------------------------------- ### inst_to_dict Example Output Source: https://docs.godotengine.org/en/4.6/classes/class_%40gdscript.html Example output from the `inst_to_dict` snippet, showing the keys and values of the generated dictionary. ```Output [@subpath, @path, foo] [, res://test.gd, bar] ``` -------------------------------- ### Example Scene Tree for HLOD Setup Source: https://docs.godotengine.org/en/4.6/tutorials/3d/visibility_ranges.html Illustrates a typical scene tree structure for setting up Hierarchical Level of Detail (HLOD) using a parent node for distant views and child nodes for closer views. ```Scene Tree ┖╴BatchOfHouses ┠╴House1 ┠╴House2 ┠╴House3 ┖╴House4 ``` -------------------------------- ### start(one_time: bool = false) Source: https://docs.godotengine.org/en/4.6/classes/class_skeletonik3d.html Starts applying IK effects on each frame to the Skeleton3D bones but will only take effect starting on the next frame. If `one_time` is `true`, this will take effect immediately but also reset on the next frame. ```APIDOC ## SkeletonIK3D.start() ### Description Starts applying IK effects on each frame to the Skeleton3D bones but will only take effect starting on the next frame. If `one_time` is `true`, this will take effect immediately but also reset on the next frame. ### Signature void start(one_time: bool = false) ### Parameters - **one_time** (bool) - Optional - If `true`, the effect takes place immediately but resets on the next frame. Defaults to `false`. ### Returns - **void** - No return value. ``` -------------------------------- ### void setup(action_map: OpenXRActionMap, interaction_profile: OpenXRInteractionProfile) Source: https://docs.godotengine.org/en/4.6/classes/class_openxrinteractionprofileeditorbase.html Initializes the editor with the specified action map and interaction profile. ```APIDOC ## Method: setup ### Description Setup this editor for the provided action map and interaction profile. ### Signature `void setup(action_map: OpenXRActionMap, interaction_profile: OpenXRInteractionProfile)` ### Parameters - **action_map** (OpenXRActionMap) - Required - The OpenXRActionMap instance to configure the editor with. - **interaction_profile** (OpenXRInteractionProfile) - Required - The OpenXRInteractionProfile instance to configure the editor with. ### Return Value `void` - This method does not return any value. ``` -------------------------------- ### setup() Source: https://docs.godotengine.org/en/4.6/classes/class_skeletonmodificationstack2d.html Sets up the modification stack for execution. ```APIDOC ## Method: void setup() ### Description Sets up the modification stack so it can execute. This function should be called by Skeleton2D and shouldn't be manually called unless you know what you are doing. ### Parameters - (None) ### Returns - (void) - No return value. ``` -------------------------------- ### start(node: StringName, reset: bool = true) Source: https://docs.godotengine.org/en/4.6/classes/class_animationnodestatemachineplayback.html Starts playback of a specific animation node within the state machine. ```APIDOC ## start(node: StringName, reset: bool = true) ### Description Starts playback of a specific animation node within the state machine. ### Method start ### Parameters #### Path Parameters - **node** (StringName) - Required - The name of the animation node to start. - **reset** (bool) - Optional - If true, resets the animation to the beginning. Defaults to true. ``` -------------------------------- ### Get Length of Variant (len) Source: https://docs.godotengine.org/en/4.6/classes/class_%40gdscript.html Examples demonstrating the `len` function to get the length of an Array and a String. `len` returns the character count for strings or element count for arrays/dictionaries. ```GDScript var a = [1, 2, 3, 4] len(a) # Returns 4 ``` ```GDScript var b = "Hello!" len(b) # Returns 6 ``` -------------------------------- ### bool start() Source: https://docs.godotengine.org/en/4.6/classes/class_godotinstance.html Finishes this instance's startup sequence. Returns `true` on success. ```APIDOC ## `bool start()` ### Description Finishes this instance's startup sequence. Returns `true` on success. ### Parameters - No parameters. ### Returns - `bool` - `true` on success, `false` otherwise. ``` -------------------------------- ### C-style For Loop Examples Source: https://docs.godotengine.org/en/4.6/tutorials/scripting/gdscript/gdscript_advanced.html Provides examples of C-style for loops with different iteration ranges and step increments. ```cpp for (int i = 0; i < 10; i++) {} ``` ```cpp for (int i = 5; i < 10; i++) {} ``` ```cpp for (int i = 5; i < 10; i += 2) {} ``` -------------------------------- ### Get Current Active State Source: https://docs.godotengine.org/en/4.6/classes/class_animationnodeoneshot.html These examples retrieve the read-only active state of the AnimationNodeOneShot. ```GDScript # Get current state (read-only). animation_tree.get("parameters/OneShot/active") # Alternative syntax (same result as above). animation_tree["parameters/OneShot/active"] ``` ```C# // Get current state (read-only). animationTree.Get("parameters/OneShot/active"); ``` -------------------------------- ### Create and Save ConfigFile Source: https://docs.godotengine.org/en/4.6/classes/class_configfile.html Demonstrates how to instantiate a ConfigFile, set values for different sections and keys, and save the configuration to a file on disk. ```GDScript # Create new ConfigFile object. var config = ConfigFile.new() # Store some values. config.set_value("Player1", "player_name", "Steve") config.set_value("Player1", "best_score", 10) config.set_value("Player2", "player_name", "V3geta") config.set_value("Player2", "best_score", 9001) # Save it to a file (overwrite if already exists). config.save("user://scores.cfg") ``` ```C# // Create new ConfigFile object. var config = new ConfigFile(); // Store some values. config.SetValue("Player1", "player_name", "Steve"); config.SetValue("Player1", "best_score", 10); config.SetValue("Player2", "player_name", "V3geta"); config.SetValue("Player2", "best_score", 9001); // Save it to a file (overwrite if already exists). config.Save("user://scores.cfg"); ``` -------------------------------- ### Manually Load, Preload, and Start Godot HTML5 Engine Source: https://docs.godotengine.org/en/4.6/tutorials/platform/web/customizing_html5_shell.html This snippet provides full control over the engine startup process. It manually initializes the engine with a WASM file, preloads the PCK file concurrently, and then starts the engine with custom arguments. ```javascript const myWasm = 'mygame.wasm'; const myPck = 'mygame.pck'; const engine = new Engine(); Promise.all([ // Load and init the engine engine.init(myWasm), // And the pck concurrently engine.preloadFile(myPck) ]).then(() => { // Now start the engine. return engine.start({ args: ['--main-pack', myPck] }); }).then(() => { console.log('Engine has started!'); }); ``` -------------------------------- ### Get Word and Line Break Positions (GDScript) Source: https://docs.godotengine.org/en/4.6/classes/class_textserver.html This example demonstrates how to obtain word break boundaries for a string, and how to use the `chars_per_line` parameter to get line break boundaries instead. ```GDScript var ts = TextServerManager.get_primary_interface() # Corresponds to the substrings "The", "Godot", "Engine", and "4". print(ts.string_get_word_breaks("The Godot Engine, 4")) # Prints [0, 3, 4, 9, 10, 16, 18, 19] # Corresponds to the substrings "The", "Godot", "Engin", and "e, 4". print(ts.string_get_word_breaks("The Godot Engine, 4", "en", 5)) # Prints [0, 3, 4, 9, 10, 15, 15, 19] # Corresponds to the substrings "The Godot" and "Engine, 4". print(ts.string_get_word_breaks("The Godot Engine, 4", "en", 10)) # Prints [0, 9, 10, 19] ``` -------------------------------- ### _shaped_text_substr(shaped: RID, start: int, length: int) Source: https://docs.godotengine.org/en/4.6/classes/class_textserverextension.html Gets a substring of the shaped text. ```APIDOC ## _shaped_text_substr ### Description Gets a substring of the shaped text. ### Signature RID _shaped_text_substr(shaped: RID, start: int, length: int) virtual required const ### Parameters - **shaped** (RID) - The resource ID of the shaped text. - **start** (int) - The starting position of the substring. - **length** (int) - The length of the substring. ### Return Value - (RID) - A new RID representing the shaped substring. ``` -------------------------------- ### void create_default_action_sets() Source: https://docs.godotengine.org/en/4.6/classes/class_openxractionmap.html Setup this action set with our default actions. ```APIDOC ## create_default_action_sets ### Description Setup this action set with our default actions. ### Method Signature void create_default_action_sets() ``` -------------------------------- ### region_get_connection_pathway_start(region: RID, connection: int) const Source: https://docs.godotengine.org/en/4.6/classes/class_navigationserver3d.html Gets the start point of a connection pathway in a region. ```APIDOC ### Method Signature Vector3 region_get_connection_pathway_start(region: RID, connection: int) const ### Description Returns the start point of a specific connection pathway within the navigation region. ### Parameters - **region** (RID) - The resource ID of the navigation region. - **connection** (int) - The index of the connection pathway. ### Returns - **Vector3** - The start point of the pathway. ``` -------------------------------- ### Initialize and Configure MultiMesh Source: https://docs.godotengine.org/en/4.6/tutorials/performance/using_multimesh.html This example demonstrates how to create and set up a MultiMesh instance, defining its transform format, total instance count, and the number of initially visible instances. It then iterates to set the individual transform for each visible instance. ```GDScript extends MultiMeshInstance3D func _ready(): # Create the multimesh. multimesh = MultiMesh.new() # Set the format first. multimesh.transform_format = MultiMesh.TRANSFORM_3D # Then resize (otherwise, changing the format is not allowed). multimesh.instance_count = 10000 # Maybe not all of them should be visible at first. multimesh.visible_instance_count = 1000 # Set the transform of the instances. for i in multimesh.visible_instance_count: multimesh.set_instance_transform(i, Transform3D(Basis(), Vector3(i * 20, 0, 0))) ``` ```C# using Godot; public partial class MyMultiMeshInstance3D : MultiMeshInstance3D { public override void _Ready() { // Create the multimesh. Multimesh = new MultiMesh(); // Set the format first. Multimesh.TransformFormat = MultiMesh.TransformFormatEnum.Transform3D; // Then resize (otherwise, changing the format is not allowed) Multimesh.InstanceCount = 1000; // Maybe not all of them should be visible at first. Multimesh.VisibleInstanceCount = 1000; // Set the transform of the instances. for (int i = 0; i < Multimesh.VisibleInstanceCount; i++) { Multimesh.SetInstanceTransform(i, new Transform3D(Basis.Identity, new Vector3(i * 20, 0, 0))); } } } ``` -------------------------------- ### Get Current Internal Active State Source: https://docs.godotengine.org/en/4.6/classes/class_animationnodeoneshot.html These examples retrieve the read-only internal active state of the AnimationNodeOneShot. ```GDScript # Get current internal state (read-only). animation_tree.get("parameters/OneShot/internal_active") # Alternative syntax (same result as above). animation_tree["parameters/OneShot/internal_active"] ``` ```C# // Get current internal state (read-only). animationTree.Get("parameters/OneShot/internal_active"); ``` -------------------------------- ### PackedByteArray get_iv_state() Source: https://docs.godotengine.org/en/4.6/classes/class_aescontext.html Get the current IV state for this context (IV gets updated when calling update()). You normally don't need this function. Note: This function only makes sense when the context is started with MODE_CBC_ENCRYPT or MODE_CBC_DECRYPT. ```APIDOC ## Method: get_iv_state() ### Description Get the current IV state for this context (IV gets updated when calling update()). You normally don't need this function. Note: This function only makes sense when the context is started with MODE_CBC_ENCRYPT or MODE_CBC_DECRYPT. ### Signature PackedByteArray get_iv_state() ### Returns - **PackedByteArray** - The current IV state. ``` -------------------------------- ### Multi-language `_Ready` Function Example Source: https://docs.godotengine.org/en/4.6/engine_details/class_reference/index.html Demonstrates the `_Ready` function implementation in both GDScript and C#, showing how to access a node and print its position. ```GDScript func _ready(): var sprite = get_node("Sprite2D") print(sprite.get_pos()) ``` ```C# public override void _Ready() { var sprite = GetNode("Sprite2D"); GD.Print(sprite.GetPos()); } ``` -------------------------------- ### Perform HTTP GET Request with GDScript HTTPClient Source: https://docs.godotengine.org/en/4.6/tutorials/networking/http_client_class.html This GDScript example demonstrates connecting to a host, sending a GET request, polling the client status, and reading the response body using Godot's HTTPClient. ```GDScript extends SceneTree # HTTPClient demo # This simple class can do HTTP requests; it will not block, but it needs to be polled. func _init(): var err = 0 var http = HTTPClient.new() # Create the Client. err = http.connect_to_host("www.php.net", 80) # Connect to host/port. assert(err == OK) # Make sure connection is OK. # Wait until resolved and connected. while http.get_status() == HTTPClient.STATUS_CONNECTING or http.get_status() == HTTPClient.STATUS_RESOLVING: http.poll() print("Connecting...") await get_tree().process_frame assert(http.get_status() == HTTPClient.STATUS_CONNECTED) # Check if the connection was made successfully. # Some headers var headers = [ "User-Agent: Pirulo/1.0 (Godot)", "Accept: */*" ] err = http.request(HTTPClient.METHOD_GET, "/ChangeLog-5.php", headers) # Request a page from the site (this one was chunked..) assert(err == OK) # Make sure all is OK. while http.get_status() == HTTPClient.STATUS_REQUESTING: # Keep polling for as long as the request is being processed. http.poll() print("Requesting...") await get_tree().process_frame assert(http.get_status() == HTTPClient.STATUS_BODY or http.get_status() == HTTPClient.STATUS_CONNECTED) # Make sure request finished well. print("response? ", http.has_response()) # Site might not have a response. if http.has_response(): # If there is a response... headers = http.get_response_headers_as_dictionary() # Get response headers. print("code: ", http.get_response_code()) # Show response code. print("**headers:\n", headers) # Show headers. # Getting the HTTP Body if http.is_response_chunked(): # Does it use chunks? print("Response is Chunked!") else: # Or just plain Content-Length var bl = http.get_response_body_length() print("Response Length: ", bl) # This method works for both anyway var rb = PackedByteArray() # Array that will hold the data. while http.get_status() == HTTPClient.STATUS_BODY: # While there is body left to be read http.poll() # Get a chunk. var chunk = http.read_response_body_chunk() if chunk.size() == 0: await get_tree().process_frame else: rb = rb + chunk # Append to read buffer. # Done! print("bytes got: ", rb.size()) var text = rb.get_string_from_ascii() print("Text: ", text) quit() ``` -------------------------------- ### submit Source: https://docs.godotengine.org/en/4.6/classes/class_renderingdevice.html Pushes the frame setup and draw command buffers then marks the local device as currently processing (which allows calling sync()). Note: Only available in local RenderingDevices. ```APIDOC ## submit ### Description Pushes the frame setup and draw command buffers then marks the local device as currently processing (which allows calling sync()). Note: Only available in local RenderingDevices. ### Method SDK Method ### Endpoint void submit() ### Parameters ### Response #### Success Response (void) - **void** - This method does not return a value. ``` -------------------------------- ### _shaped_text_get_selection(shaped: RID, start: int, end: int) Source: https://docs.godotengine.org/en/4.6/classes/class_textserverextension.html Gets the selection geometry for a given range in the shaped text. ```APIDOC ## _shaped_text_get_selection ### Description Gets the selection geometry for a given range in the shaped text. ### Signature PackedVector2Array _shaped_text_get_selection(shaped: RID, start: int, end: int) virtual const ### Parameters - **shaped** (RID) - The resource ID of the shaped text. - **start** (int) - The starting position of the selection. - **end** (int) - The ending position of the selection. ### Return Value - (PackedVector2Array) - An array of Vector2 representing the selection geometry. ``` -------------------------------- ### create_server(port: int, max_clients: int = 32, max_channels: int = 0, in_bandwidth: int = 0, out_bandwidth: int = 0) Source: https://docs.godotengine.org/en/4.6/classes/class_enetmultiplayerpeer.html Initializes the peer as a server. ```APIDOC ## Method: create_server ### Signature Error create_server(port: int, max_clients: int = 32, max_channels: int = 0, in_bandwidth: int = 0, out_bandwidth: int = 0) ### Parameters - **port** (int) - **max_clients** (int) - Default: 32 - **max_channels** (int) - Default: 0 - **in_bandwidth** (int) - Default: 0 - **out_bandwidth** (int) - Default: 0 ### Returns Error ``` -------------------------------- ### Get Property Subname by Index (GDScript/C#) Source: https://docs.godotengine.org/en/4.6/classes/class_nodepath.html Retrieve a specific property subname from a NodePath by its index. Indices start from 0. ```GDScript var path_to_name = NodePath("Sprite2D:texture:resource_name") print(path_to_name.get_subname(0)) # Prints "texture" print(path_to_name.get_subname(1)) # Prints "resource_name" ``` ```C# var pathToName = new NodePath("Sprite2D:texture:resource_name"); GD.Print(pathToName.GetSubname(0)); // Prints "texture" GD.Print(pathToName.GetSubname(1)); // Prints "resource_name" ``` -------------------------------- ### Create a new Godot project from the command line Source: https://docs.godotengine.org/en/4.6/tutorials/editor/command_line_tutorial.html Use these bash commands to initialize a new Godot project by creating a dedicated directory and an empty project.godot file within it. ```bash mkdir newgame cd newgame touch project.godot ``` -------------------------------- ### _shaped_text_get_dominant_direction_in_range(shaped: RID, start: int, end: int) Source: https://docs.godotengine.org/en/4.6/classes/class_textserverextension.html Gets the dominant direction within a specified range of the shaped text. ```APIDOC ## _shaped_text_get_dominant_direction_in_range ### Description Gets the dominant direction within a specified range of the shaped text. ### Signature int _shaped_text_get_dominant_direction_in_range(shaped: RID, start: int, end: int) virtual const ### Parameters - **shaped** (RID) - The resource ID of the shaped text. - **start** (int) - The starting position of the range. - **end** (int) - The ending position of the range. ### Return Value - (int) - The dominant direction. ``` -------------------------------- ### get_is_setup() Source: https://docs.godotengine.org/en/4.6/classes/class_skeletonmodification2d.html Indicates whether the modification has been successfully initialized. ```APIDOC ## Method: get_is_setup() const ### Description Returns whether this modification has been successfully setup or not. ### Parameters (None) ### Returns bool - `true` if the modification is set up, `false` otherwise. ``` -------------------------------- ### Get Node Name by Index (GDScript/C#) Source: https://docs.godotengine.org/en/4.6/classes/class_nodepath.html Access a specific node name within a NodePath by its index. Indices start from 0. ```GDScript var sprite_path = NodePath("../RigidBody2D/Sprite2D") print(sprite_path.get_name(0)) # Prints ".." print(sprite_path.get_name(1)) # Prints "RigidBody2D" print(sprite_path.get_name(2)) # Prints "Sprite" ``` ```C# var spritePath = new NodePath("../RigidBody2D/Sprite2D"); GD.Print(spritePath.GetName(0)); // Prints ".." GD.Print(spritePath.GetName(1)); // Prints "PathFollow2D" GD.Print(spritePath.GetName(2)); // Prints "Sprite" ``` -------------------------------- ### Engine.prototype.preloadFile(file[, path]) Source: https://docs.godotengine.org/en/4.6/tutorials/platform/web/html5_shell_classref.html Load a file so it is available in the instance's file system once it runs. Must be called **before** starting the instance. ```APIDOC ## INSTANCE METHOD Engine.prototype.preloadFile(file[, path]) ### Description Load a file so it is available in the instance's file system once it runs. Must be called **before** starting the instance. If not provided, the `path` is derived from the URL of the loaded file. ### Arguments - **file** (string|ArrayBuffer()) - Required - The file to preload. If a `string` the file will be loaded from that path. If an `ArrayBuffer` or a view on one, the buffer will used as the content of the file. - **path** (string()) - Optional - Path by which the file will be accessible. Required, if `file` is not a string. ### Returns A Promise that resolves once the file is loaded. ``` -------------------------------- ### create_client(address: String, port: int, channel_count: int = 0, in_bandwidth: int = 0, out_bandwidth: int = 0, local_port: int = 0) Source: https://docs.godotengine.org/en/4.6/classes/class_enetmultiplayerpeer.html Initializes the peer as a client. ```APIDOC ## Method: create_client ### Signature Error create_client(address: String, port: int, channel_count: int = 0, in_bandwidth: int = 0, out_bandwidth: int = 0, local_port: int = 0) ### Parameters - **address** (String) - **port** (int) - **channel_count** (int) - Default: 0 - **in_bandwidth** (int) - Default: 0 - **out_bandwidth** (int) - Default: 0 - **local_port** (int) - Default: 0 ### Returns Error ``` -------------------------------- ### preprocess Property Accessors Source: https://docs.godotengine.org/en/4.6/classes/class_cpuparticles3d.html Methods to get and set the `preprocess` property, which defines how many seconds the particle system starts as if it had already run. ```APIDOC ## set_pre_process_time ### Description Sets the `preprocess` property. Particle system starts as if it had already run for this many seconds. ### Method Signature void set_pre_process_time(value: float) ### Parameters #### Method Parameters - **value** (float) - Required - The new float value for `preprocess`. ## get_pre_process_time ### Description Retrieves the current value of the `preprocess` property. ### Method Signature float get_pre_process_time() ### Return Value - **float** - The current float value of `preprocess`. ``` -------------------------------- ### Install Godot Editor with Scoop (Windows) Source: https://docs.godotengine.org/en/4.6/tutorials/editor/command_line_tutorial.html Use Scoop to install the standard Godot editor or the C# supported version on Windows, making it available in the system's PATH. ```bash # Add "Extras" bucket scoop bucket add extras # Standard editor: scoop install godot # Editor with C# support (will be available as `godot-mono` in `PATH`): scoop install godot-mono ``` -------------------------------- ### Absolute NodePaths in GDScript Source: https://docs.godotengine.org/en/4.6/classes/class_nodepath.html These examples show how to define absolute node paths, starting from the SceneTree's root using a leading slash. ```GDScript ^"/root" # Points to the SceneTree's root Window. ^"/root/Title" # May point to the main scene's root node named "Title". ^"/root/Global" # May point to an autoloaded node or scene named "Global". ``` -------------------------------- ### pck_start(pck_path: String, alignment: int = 32, key: String = "0000000000000000000000000000000000000000000000000000000000000000", encrypt_directory: bool = false) Source: https://docs.godotengine.org/en/4.6/classes/class_pckpacker.html Creates a new PCK file at the file path pck_path. The .pck file extension isn't added automatically, so it should be part of pck_path (even though it's not required). ```APIDOC ## Method: pck_start ### Description Creates a new PCK file at the file path pck_path. The .pck file extension isn't added automatically, so it should be part of pck_path (even though it's not required). ### Signature pck_start(pck_path: String, alignment: int = 32, key: String = "0000000000000000000000000000000000000000000000000000000000000000", encrypt_directory: bool = false) ### Parameters - **pck_path** (String) - Required - Path for the new PCK file. The `.pck` extension should be included. - **alignment** (int) - Optional - Alignment for the PCK file. Default is `32`. - **key** (String) - Optional - Encryption key. Default is a string of zeros. - **encrypt_directory** (bool) - Optional - Whether to encrypt the directory. Default is `false`. ### Returns Error ``` -------------------------------- ### region_get_closest_point_to_segment(region: RID, start: Vector3, end: Vector3, use_collision: bool = false) const Source: https://docs.godotengine.org/en/4.6/classes/class_navigationserver3d.html Gets the closest point on a navigation region to a line segment. ```APIDOC ### Method Signature Vector3 region_get_closest_point_to_segment(region: RID, start: Vector3, end: Vector3, use_collision: bool = false) const ### Description Returns the closest point on the navigation mesh within the specified region to a given line segment. ### Parameters - **region** (RID) - The resource ID of the navigation region. - **start** (Vector3) - The start point of the segment. - **end** (Vector3) - The end point of the segment. - **use_collision** (bool) - Optional - If `true`, considers collision geometry. Defaults to `false`. ### Returns - **Vector3** - The closest point on the navigation mesh to the segment. ``` -------------------------------- ### Complete Script Documentation Example (GDScript) Source: https://docs.godotengine.org/en/4.6/tutorials/scripting/gdscript/gdscript_documentation_comments.html A comprehensive example demonstrating documentation for a class, signals, enums, constants, variables (including exported and typed), functions (including private but documented), and inner classes with their members. ```GDScript extends Node2D ## A brief description of the class's role and functionality. ## ## The description of the script, what it can do, ## and any further detail. ## ## @tutorial: https://example.com/tutorial_1 ## @tutorial(Tutorial 2): https://example.com/tutorial_2 ## @experimental ## The description of a signal. signal my_signal ## This is a description of the below enum. enum Direction { ## Direction up. UP = 0, ## Direction down. DOWN = 1, ## Direction left. LEFT = 2, ## Direction right. RIGHT = 3, } ## The description of a constant. const GRAVITY = 9.8 ## The description of the variable v1. var v1 ## This is a multiline description of the variable v2.[br] ## The type information below will be extracted for the documentation. var v2: int ## If the member has any annotation, the annotation should ## immediately precede it. @export var v3 := some_func() ## As the following function is documented, even though its name starts with ## an underscore, it will appear in the help window. func _fn(p1: int, p2: String) -> int: return 0 # The below function isn't documented and its name starts with an underscore # so it will treated as private and will not be shown in the help window. func _internal() -> void: pass ## Documenting an inner class. ## ## The same rules apply here. The documentation must ## immediately precede the class definition. ## ## @tutorial: https://example.com/tutorial ## @experimental class Inner: ## Inner class variable v4. var v4 ## Inner class function fn. func fn(): pass ``` -------------------------------- ### Get Pretty Node Tree String Source: https://docs.godotengine.org/en/4.6/classes/class_node.html This snippet shows an example output of the `get_tree_string_pretty()` method, providing a graphical representation of the scene tree for easier inspection. ```Output ┖╴TheGame ┠╴Menu ┃ ┠╴Label ┃ ┖╴Camera2D ┖╴SplashScreen ┖╴Camera2D ``` -------------------------------- ### _initialize(project_path: String) Source: https://docs.godotengine.org/en/4.6/classes/class_editorvcsinterface.html Initializes the VCS plugin for a given project path, returning true on success. ```APIDOC ## Method: _initialize ### Description Initializes the VCS plugin for a given project path. Returns whether the plugin was successfully initialized. ### Signature bool _initialize(project_path: String) ### Parameters - **project_path** (String) - The path to the project where the VCS should be initialized. ### Returns (bool) - `true` if the plugin was successfully initialized, `false` otherwise. ``` -------------------------------- ### create_offer() Source: https://docs.godotengine.org/en/4.6/classes/class_webrtcpeerconnection.html Initiates the WebRTC connection process by creating an SDP offer. ```APIDOC ## create_offer ### Description Initiates the WebRTC connection process by creating an SDP offer. This will trigger the `session_description_created` signal. ### Method create_offer ```