These instructions assume you have already started a new project and are looking at a fresh, empty workspace.

In this tutorial, we're going to create our first program. Traditionally, the first program that any programmer, even seasoned programmers, would write in a new language is something called Hello World a simple program that merely prints to the screen the phrase "Hello World." While this is usually very simple to achieve, it can be very useful in demonstrating the rules, syntax and structure of the program and affirming that all the necessary tools are properly installed and functioning.
To print the phrase "Hello World" to our screen we will need a script, but first we need a node to which we may attach that script, and a scene in which to save that node.
In the Scene dock, click "3D Scene." This will create a new 3D scene with a "Spatial" node as its root. Then select the Spatial node and click the "Attach Script" button on the top-right of the dock.

On the screen that comes up, you don't need to change anything. If this were a larger program, you might want to save this script in a "Scripts" folder within your project, but don't worry about that for now. Just click the "Load" button.

You should now see the default template in your Script workspace.

Delete everything that's there and write the following code.

That's it! "extends Spatial" allows this code to use any method (built-in function) that a spatial node would have. The function named "_ready" is one of these, a special function called once and only once when the script is first read. The "print" command will print the data within the parentheses to the console, something we'll look at in a minute. By putting the phrase "Hello World" in quotation marks we indicate that it is a string data type.
Therefore, when we run our game, "Hello World" will print once to the console.
To test it, we first need to save. Press CTRL+S or go to Scene - Save Scene. Rename the file to "HelloWorld.tscn" and press "Save." If this were a larger project, you would probably want to create a "Scenes" folder to put it in, but you don't need to worry about that right now.
Press the play button at the top right of the screen.

You should get a warning that you do not yet have a main scene to play. Press the "Select" button, then choose "HelloWorld.tscn" and press "Open." This will confirm that you would like to make this scene the first one that opens when you play your game.
You will see a blank, gray screen. This is because there is no camera yet in your scene from which to view the 3D environment. That's fine, we're only interested in the console. If you look at the bottom left of your main editor now, you should see the words "Hello World" appear in the output.

Congratulations! You made your first program! Close the gray window or press the the stop button to exit your game.
No comments:
Post a Comment