GDScript Print Tutorial – Complete Guide

Unlock the power of GDScript with our in-depth and beginner-friendly guide on understanding and implementing the ‘print’ command in your Godot games. Created with both novice and experienced coders in mind, we delve into the world of GDScript to highlight its ease of use and versatility in game development projects. But, let’s take things step by step.

What is GDScript ‘print’?

GDScript is Godot’s built-in scripting language, designed to blend seamlessly with the game engine while keeping the language easy to learn and user-friendly. Among the basic commands in GDScript, the ‘print’ function stands out as a vital debugging and logging tool for developers.

The ‘print’ command in GDScript does exactly what it sounds like – it prints information to the console. This can be invaluable when trying to troubleshoot problems in your code, allowing you to track variables, view object states, or simply make sure the code is working as intended.

Why learn GDScript ‘print’?

Understanding and effectively using the ‘print’ function in GDScript can drastically enhance your coding proficiency, and ultimately, your game development process. With it, you can easily monitor the states of your objects, the values of your variables, script execution order, and get a real-time understanding of what exactly your code is doing. This hands-on visibility can prove the difference between a bug-riddled project and a smoothly running game.

Moreover, GDScript and its commands, like ‘print’, are a fantastic entry point for aspiring game developers with little to no prior programming experience. It provides a beginner-friendly syntax, low learning curve, and powerful capabilities—making it a potent tool for both novices and seasoned developers.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Basic Usage of ‘print’ in GDScript

Let’s start with the basic usage of the ‘print’ command. In its simplest form, it prints a literal string or a variable’s value to your console. It’s a straightforward but powerful tool in your GDScript arsenal.

print("Hello, Zenva Academy!")
myVariable = "Welcome to GDScript lesson!"
print(myVariable)

In the above example, ‘Hello, Zenva Academy!’ and ‘Welcome to GDScript lesson!’ will be printed on the console.

Printing Multiple Items

You can print multiple values at once with the ‘print’ command in GDScript. It is as easy as adding a comma between each item you want to print.

playerScore = 100
playerHealth = 75
print("Score:", playerScore, "Health:", playerHealth)

In the above example, ‘Score: 100 Health: 75’ will be printed on the console.

Formatting with ‘print’

You can also use GDScript’s ‘print’ function to format your output data. For this, all you need to do is use the ‘%’ character, followed by the format specifier.

playerScore = 100
print("Score: %d" % playerScore)

The above example will print ‘Score: 100’ to the console.

Debugging with ‘print’

The ‘print’ command is great for keeping track of your code execution and errors. Here is how:

 
print("Line 1 executed")
playerHealth = 75
print("Line 2 executed || player health:", playerHealth)

The ‘print’ commands here will show you the order of execution and the player’s health inline with the execution message in console.

Conditional Debugging with ‘print’

‘print’ can also be coupled with conditional statements to give you more precise control over its execution. Let’s explore this:

playerHealth = 75
if playerHealth < 100:
  print("Player needs healing")

The ‘print’ command here will execute only if the player’s health is less than 100, printing ‘Player needs healing’ to the console.

Loop Iterations and ‘print’

Visualizing loop iterations is another handy use for the ‘print’ function. With a simple ‘for’ loop, we can demonstrate this:

for i in range(5):
  print("Iteration ", i)

Running this script will print ‘Iteration 0’, ‘Iteration 1’, and so on, up to ‘Iteration 4’.

Printing Arrays

You can utilize ‘print’ to kinetically visualize your array’s content as well:

playerInventory = ["Sword", "Shield", "Potion"]
print(playerInventory)

The output will be the array ‘[Sword, Shield, Potion]’. You can also print a specific array element:

print(playerInventory[0])

The above script will print ‘Sword’, the first item in the playerInventory array.

‘Print’ in Custom Functions

‘print’ is indeed invaluable within custom functions for tracking values and condition block execution. Let’s take a look:

func calculateDamage(playerAttack, enemyDefense):
  damage = playerAttack - enemyDefense
  print("Calculated damage is ", damage)

Here, the ‘print’ command is used to output the damage calculated within a custom function, which aids in verifying the calculations and output of the function.

Integrating ‘print’ with Node Properties

In Godot, each object in your game is considered a node with various properties. Using the ‘print’ command, you can easily output these properties to monitor changes in their states.

var playerPos = $Player.position
print(playerPos)

In this example, the player’s current position on the 2D plane would be printed on the console.

‘Print’ with Signals

Signals in Godot are a way of handling events. By utilizing the ‘print’ command in signals, you can confirm signal emission and execution of connected functions.

func _on_bullet_hitting_enemy():
  print("Bullet hit enemy successfully!")

In this script, a message will be printed in the console when the signal function “_on_bullet_hitting_enemy” is triggered.

Printing Details of Instances

When dealing with instances in your Godot projects, the ‘print’ function can be used to output the instance’s details.

var player = Player.new()
print(player)

The output here will be the instance reference of the newly created player.

Using ‘print’ in Error Handling

‘Print’ is a crucial function to utilize during error handling in GDScript. You can use it to output error messages and catch exceptions in your code.

func divide(a, b):
  if b != 0:
    print(a / b)
  else:
    print("Error: Division by zero is not allowed!")

In this case, the ‘print’ command outputs an error message when there’s an attempt to divide by zero.

Printing Dictionary Elements

Often in game development, we rely on complex data structures like dictionaries. The ‘print’ command can be immensely helpful in displaying its content.

var playerStats = {"Attack":50, "Defense":40, "Speed":30}
print(playerStats)

Here, the ‘print’ command will output the entire dictionary on the console.

Advanced Functionality of ‘print’

Finally, let’s have a look at how ‘print’ can be used as a potent debugging tool in the realm of multi-threading.

func _thread_function():
  print("Thread started at ", OS.get_time())

In the context of the thread, ‘print’ will output the exact time of the thread’s commencement.

Mastery of the GDScript ‘print’ command is just the first step on a larger journey. Diving deeper into GDScript and Godot’s potential will unlock the gateway to creating interactive, immersive, and fun games. We at Zenva, encourage you to keep exploring, experimenting, and learning.

Looking for a structured path to progress on this journey? Consider checking out our Godot Game Development Mini-Degree. This comprehensive curriculum is a suite of courses designed to guide you in building games using the Godot 4 engine. You’ll tackle various facets of game development, all the while accumulating a portfolio of real Godot projects to showcase your burgeoning skills.

For a more general take on Godot-related education, do explore our library of Godot Courses. Our courses span a variety of topics, catering to different experience levels, so no matter your prior knowledge or skills, with Zenva, you are on a sure way from beginner to professional.

Conclusion

Whether it’s tracking variables, monitoring game state changes, or aiding in debugging, the ‘print’ command in GDScript is a fundamental tool in a game developer’s toolkit. With our comprehensive breakdown of ‘print’ usage, we hope to have demonstrated its flexibility and utility in your game development endeavours.

At Zenva, we thrive on demystifying coding and game creation to empower a new generation of developers. Begin building games, start your programming journey, and harness the power of GDScript today with our Godot Game Development Mini-Degree. We look forward to fostering your growth and playing your amazing Godot games in the future!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.