Recomendaciones de lógica
Alguna vez te has preguntado si uno debe enfocarse en un problema X con una estrategia Y o Z? Este articulo cubre una variedad de temas relacionados a estos dilemas.
Agregar nodos y cambiar propiedades: ¿qué es lo primero?
Cuando se inicializan nodos de un script en tiempo de ejecución, puede que necesites cambiar propiedades como el nombre o la posición del nodo. Un dilema común es ¿cuándo deberías cambiar estos valores?
It is the best practice to change values on a node before adding it to the scene tree. Some properties' setters have code to update other corresponding values, and that code can be slow! For most cases, this code has no impact on your game's performance, but in heavy use cases such as procedural generation, it can bring your game to a crawl.
For these reasons, it is usually best practice to set the initial values of a node before adding it to the scene tree. There are some exceptions where values can't be set before being added to the scene tree, like setting global position.
Cargar (load) vs. pre-cargar (preload)
En GDScript, existe el método global preload. El carga los recursos lo más rapido posible para cargar frontalmente las operaciones de "carga" y evitar el cargar recursos mientras se encuentra en medio del código que se considera sensitivo para el rendimiento.
Su contraparte, el metodo load, carga un recurso solo cuando este llega a la declaración de carga. Esto es, el va a cargar un recurso en su lugar, y puede causar ralentizamiento en el medio de procesos importantes. La función de load() también es un alias de ResourceLoader.load(path) que es accesible a todos los lenguajes de scripting.
Entonces, cuando el precargar exactamente ocurre versus el cargar, y cuando uno debería de usar cualquiera de los dos? veamos un ejemplo:
# my_buildings.gd
extends Node
# Note how constant scripts/scenes have a different naming scheme than
# their property variants.
# This value is a constant, so it spawns when the Script object loads.
# The script is preloading the value. The advantage here is that the editor
# can offer autocompletion since it must be a static path.
const BuildingScn = preload("res://building.tscn")
# 1. The script preloads the value, so it will load as a dependency
# of the 'my_buildings.gd' script file. But, because this is a
# property rather than a constant, the object won't copy the preloaded
# PackedScene resource into the property until the script instantiates
# with .new().
#
# 2. The preloaded value is inaccessible from the Script object alone. As
# such, preloading the value here actually does not provide any benefit.
#
# 3. Because the user exports the value, if this script stored on
# a node in a scene file, the scene instantiation code will overwrite the
# preloaded initial value anyway (wasting it). It's usually better to
# provide `null`, empty, or otherwise invalid default values for exports.
#
# 4. Instantiating the script on its own with .new() triggers
# `load("office.tscn")`, ignoring any value set through the export.
@export var a_building : PackedScene = preload("office.tscn")
# Uh oh! This results in an error!
# One must assign constant values to constants. Because `load` performs a
# runtime lookup by its very nature, one cannot use it to initialize a
# constant.
const OfficeScn = load("res://office.tscn")
# Successfully loads and only when one instantiates the script! Yay!
var office_scn = load("res://office.tscn")
using Godot;
// C# and other languages have no concept of "preloading".
public partial class MyBuildings : Node
{
//This is a read-only field, it can only be assigned when it's declared or during a constructor.
public readonly PackedScene Building = ResourceLoader.Load<PackedScene>("res://building.tscn");
public PackedScene ABuilding;
public override void _Ready()
{
// Can assign the value during initialization.
ABuilding = GD.Load<PackedScene>("res://Office.tscn");
}
}
using namespace godot;
class MyBuildings : public Node {
GDCLASS(MyBuildings, Node)
public:
const Ref<PackedScene> building = ResourceLoader::get_singleton()->load("res://building.tscn");
Ref<PackedScene> a_building;
virtual void _ready() override {
// Can assign the value during initialization.
a_building = ResourceLoader::get_singleton()->load("res://office.tscn");
}
};
Preloading allows the script to handle all the loading the moment one loads the script. Preloading is useful, but there are also times when one doesn't wish to use it. Here are a few considerations when determining which to use:
If one cannot determine when the script might load, then preloading a resource (especially a scene or script) could result in additional loads one does not expect. This could lead to unintentional, variable-length load times on top of the original script's load operations.
Si algo puede reemplazar el valor (como la inicialización de una escena exportada), entonces precargar el valor no tiene sentido. Este punto no es un factor significante si uno quiere crear siempre los scripts.
Si uno sólo desea 'importar' otro recurso de clase (script o escena), entonces usar una constante precargada es a menudo el mejor curso de acción. Sin embargo, en casos excepcionales, es posible que no desee hacer esto:
Si la clase 'importada' es capaz de ser modificada, entonces debería ser una propiedad, inicializada ya sea con un
exporto unload()(y tal vez no inicializada sino más adelante).If the script requires a great many dependencies, and one does not wish to consume so much memory, then one may wish to load and unload various dependencies at runtime as circumstances change. If one preloads resources into constants, then the only way to unload these resources would be to unload the entire script. If they are instead loaded as properties, then one can set these properties to
nulland remove all references to the resource (which, as a RefCounted-extending type, will cause the resources to delete themselves from memory).
Niveles grandes: estático vs dinámico
If one is creating a large level, which circumstances are most appropriate? Is it better to create the level as one static space? Or is it better to load the level in pieces and shift the world's content as needed?
Bien, la respuesta simple es "cuando la performance lo requiera". El dilema asociado con las dos opciones es una de las viejas opciones de programación: se optimiza memoria por sobre velocidad o viceversa?
La respuesta inexperta es de usar un nivel estático que cargue todo de una vez pero, dependiendo del proyecto, esto puede consumir una gran cantidad de memoria. El desperdicio de la RAM de los usuario hace que los programas comiencen a funcionar más lento o directamente cuelgues de cualquier otra cosa que la computadora esté tratando de ejecutar al mismo tiempo.
Sin importar qué, se debe romper escenas largas en otras más pequeñas (para ayudar en la reusabilidad de contenido). Los desarrolladores pueden entonces designar un nodo que manipule la creación/carga y borrado/descarga de recursos y nodos en tiempo real. Juegos con gra variedad y tamaño de entornos o elementos generados proceduralmente normalmente emplean esas estrategias para evitar desperdiciar memoria.
On the flip side, coding a dynamic system is more complex; it uses more programmed logic which results in opportunities for errors and bugs. If one isn't careful, they can develop a system that bloats the technical debt of the application.
Como tales, las mejores opciones serían...
Use static levels for smaller games.
If one has the time/resources on a medium/large game, create a library or plugin that can manage nodes and resources with code. If refined over time so as to improve usability and stability, then it could evolve into a reliable tool across projects.
Use dynamic logic for a medium/large game because one has the coding skills, but not the time or resources to refine the code (game's gotta get done). Could potentially refactor later to outsource the code into a plugin.
Para ejemplos de los varios modos en que se pueden cambiar escenas en tiempo de ejecución, lee la documentación de "Cambiar escenas manualmente".