Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Creating instances

Nella parte precedente abbiamo visto che una scena è un insieme di nodi organizzati in una struttura ad albero, con un singolo nodo come radice. È possibile suddividere il progetto in un numero qualsiasi di scene. Questa funzione aiuta a suddividere e organizzare i diversi componenti del gioco.

You can create as many scenes as you'd like and save them as files with the .tscn extension, which stands for "text scene". The label.tscn file from the previous lesson was an example. We call those files "Packed Scenes" as they pack information about your scene's content.

Here's an example of a ball. It's composed of a RigidBody2D node as its root named Ball, which allows the ball to fall and bounce on walls, a Sprite2D node, and a CollisionShape2D.

../../_images/instancing_ball_scene.png

Una volta salvata una scena, questa funziona come un modello: si può riprodurre in altre scene tutte le volte che si vuole. La replica di un oggetto da un modello come questo si chiama instancing (Instanza).

../../_images/instancing_ball_instances_example.png

Come abbiamo detto nella parte precedente, le scene istanziate si comportano come un nodo: l'editor nasconde il loro contenuto per impostazione predefinita. Quando si istanzia la Palla, si vede solo il nodo Palla. Si noti anche come ogni duplicato abbia un nome unico.

Every instance of the Ball scene starts with the same structure and properties as ball.tscn. However, you can modify each independently, such as changing how they bounce, how heavy they are, or any property exposed by the source scene.

In pratica

Let's use instancing in practice to see how it works in Godot. We invite you to download the ball's sample project we prepared for you: instancing_starter.zip.

Extract the archive on your computer. To import it, you need the Project Manager. The Project Manager is accessed by opening Godot, or if you already have Godot opened, click on Project -> Quit to Project List (Ctrl + Shift + Q, Ctrl + Option + Cmd + Q on macOS)

In the Project Manager, click the Import button to import the project.

../../_images/instancing_import_button.png

Nel pop-up che appare, fare clic sul pulsante Sfoglia e navigare nella cartella estratta.

../../_images/instancing_import_browse.png

Fare doppio clic sul file project.godot per aprirlo.

../../_images/instancing_import_project_file.png

Infine, fare clic sul pulsante 'Importa e Modifica'.

../../_images/instancing_import_and_edit_button.png

The project contains two packed scenes: main.tscn, containing walls against which the ball collides, and ball.tscn. The Main scene should open automatically. If you're seeing an empty 3D scene instead of the main scene, click the 2D button at the top of the screen.

../../_images/instancing_2d_scene_select.webp ../../_images/instancing_main_scene.png

Aggiungiamo una palla come figlio del nodo Main. Nel dock della scena, selezionare il nodo Main. Quindi, fare clic sull'icona di collegamento nella parte superiore del dock della scena. Questo pulsante consente di aggiungere un'istanza di una scena come figlio del nodo attualmente selezionato.

../../_images/instancing_scene_link_button.png

Fare doppio clic sulla scena della palla per istanziarla.

../../_images/instancing_instance_child_window.png

The ball appears in the top-left corner of the viewport.

../../_images/instancing_ball_instanced.png

Fare clic su di esso e trascinarlo verso il centro della vista.

../../_images/instancing_ball_moved.png

Play the game by pressing F5 (Cmd + B on macOS). You should see it fall.

Now, we want to create more instances of the Ball node. With the ball still selected, press Ctrl + D (Cmd + D on macOS) to call the duplicate command. Click and drag to move the new ball to a different location.

../../_images/instancing_ball_duplicated.png

You can repeat this process until you have several in the scene.

../../_images/instancing_main_scene_with_balls.png

Eseguire nuovamente il gioco. Ora dovreste vedere ogni palla cadere indipendentemente l'una dall'altra. Questo è ciò che fanno le istanze. Ognuna è una riproduzione indipendente di una scena template (modello).

Editing scenes and instances

C'è ancora altro sulle istanze. Con questa funzione è possibile:

  1. Modificare le proprietà di una sfera senza influenzare le altre utilizzando l'Inspector.

  2. Change the default properties of every Ball by opening the ball.tscn scene and making a change to the Ball node there. Upon saving, all instances of the Ball in the project will see their values update.

Nota

La modifica di una proprietà su un'istanza sovrascrive sempre i valori della scena impacchettata corrispondente.

Let's try this. Open ball.tscn and select the Ball node. In the Inspector on the right, click on the PhysicsMaterial property to expand it.

../../_images/instancing_physics_material_expand.webp

Set its Bounce property to 0.5 by clicking on the number field, typing 0.5, and pressing Enter.

../../_images/instancing_property_bounce_updated.webp

Eseguire il gioco premendo F5 e notare come tutte le palle ora rimbalzino molto di più. Poiché la scena Ball è un modello per tutte le istanze, modificandola e salvandola tutte le istanze si aggiornano di conseguenza.

Regoliamo ora una singola istanza. Tornare alla scena principale facendo clic sulla scheda corrispondente sopra la finestra di visualizzazione.

../../_images/instancing_scene_tabs.png

Selezionate uno dei nodi Ball istanziati e, nell'Inspector, impostate il valore Gravity Scale su 10.

../../_images/instancing_property_gravity_scale.png

Accanto alla proprietà modificata viene visualizzato il pulsante grigio "revert" (ripristina).

../../_images/instancing_property_revert_icon.png

This icon indicates you are overriding a value from the source packed scene. Even if you modify the property in the original scene, the value override will be preserved in the instance. Clicking the revert icon will restore the property to the value in the saved scene.

Riprendete il gioco e notate che questa palla ora cade molto più velocemente delle altre.

Nota

Se si modifica un valore del PhysicsMaterial di un'istanza, questo avrà effetto su tutte le altre. Questo perché PhysicsMaterial è una risorsa e le risorse sono condivise tra le istanze. Per rendere una risorsa unica per un'istanza, fate clic con il pulsante destro del mouse su di essa nell'Inspector e fate clic su Rendi unica nel menu contestuale.

Le risorse sono un altro elemento essenziale dei giochi di Godot, che tratteremo in una lezione successiva.

Istanze di scena come linguaggio di design

Le istanze e le scene in Godot offrono un linguaggio di progettazione eccellente, che distingue il motore da altri esistenti. Abbiamo progettato Godot intorno a questo concetto fin dall'inizio.

Quando si realizzano giochi con Godot, si consiglia di evitare i normali Desing patterns, come MVC (Model-View-Controller) o Entity-Relationship. Si può invece iniziare immaginando gli elementi che i giocatori vedranno nel gioco e strutturando il codice intorno ad essi.

For example, you could break down a shooter game like so:

../../_images/instancing_diagram_shooter.png

You can come up with a diagram like this for almost any type of game. Each rectangle represents an entity that's visible in the game from the player's perspective. The arrows tell you which scene owns which.

Once you have a diagram, we recommend creating a scene for each element listed in it to develop your game. You'll use instancing, either by code or directly in the editor, to build your tree of scenes.

Programmers tend to spend a lot of time designing abstract architectures and trying to fit components into it. Designing based on scenes makes development faster and more straightforward, allowing you to focus on the game logic itself. Because most game components map directly to a scene, using a design based on scene instantiation means you need little other architectural code.

Here's the example of a scene diagram for an open-world game with tons of assets and nested elements:

../../_images/instancing_diagram_open_world.png

Immaginiamo di iniziare creando la stanza. Potremmo creare un paio di scene di stanze diverse, con una disposizione unica dei mobili al loro interno. In seguito, potremmo creare una scena di una casa che utilizza istanze multiple per gli interni. Creeremo una cittadella con molte istanze di case e un grande terreno su cui posizionare la cittadella. Ognuno di questi elementi sarebbe una scena che istanzia una o più sotto-scene.

Later, we could create scenes representing guards and add them to the citadel. They would be indirectly added to the overall game world.

With Godot, it's easy to iterate on your game like this, as all you need to do is create and instantiate more scenes. We designed the editor to be accessible to programmers, designers, and artists alike. A typical team development process can involve 2D or 3D artists, level designers, game designers, and animators, all working with the Godot editor.

Sommario

Instancing, the process of producing an object from a blueprint, has many handy uses. With scenes, it gives you:

  • The ability to divide your game into reusable components.

  • Uno strumento per strutturare e incapsulare sistemi complessi.

  • Un linguaggio pensato per concepire la struttura del vostro progetto di gioco in modo naturale.