Array in Godot – Complete Guide

Arrays are one of the most fundamental data structures in any programming language, and Godot’s scripting languages are no exception. Whether you’re new to coding, taking your first steps in game development, or an experienced developer looking to fine-tune your scripting skills, understanding arrays is crucial for managing collections of data in a structured manner. In this tutorial, we’ll explore the Array class in Godot 4, a powerful engine that makes game development more accessible and fun. We’ll dive deep into its usage within the context of game scripting to bring your creations to life.

What Is an Array?

An array, in the context of Godot, is a built-in data structure that holds a sequence of elements that can be of any type. This versatility allows for a wide range of applications, from simple lists to complex data management. Arrays are accessed via numerical indices, with the counting starting from 0 for the first element.

What Is It For?

Arrays are incredibly useful for storing collections of items such as inventory items in a game, waypoints in a path, or even high scores. They’re the backbone for many common game mechanics, acting as containers that programmers can manipulate to track and control game states and behaviors.

Why Should I Learn It?

Understanding arrays is an essential skillset for any Godot developer. They form the basis for organizing objects and information, making your code more efficient, legible, and ultimately, your game more dynamic. By mastering arrays, you can handle complex tasks like spawning enemies, managing player inventory, and much more with ease. So, let’s gear up and dive into the world of arrays in Godot 4!

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

Creating and Initializing Arrays

In Godot, you can create an Array in several ways, and initialization is just as flexible. To start using arrays in your projects, let’s go through some basic examples of how to create and initialize them.

var my_first_array = Array()            # An empty array
var my_second_array = []                # Another empty array, using shorthand notation
var inventory = ["sword", "shield", "potion"] # An array pre-filled with strings

Godot’s dynamic typing allows array elements to be of any type, even within the same array:

var mixed_array = [42, "hello", true, null] # An array with various data types

Array Manipulation: Adding and Removing Elements

Adding and removing elements from arrays is a common requirement in game development. In Godot, you can manage arrays with simple methods:

# Adding elements to the end of the array
inventory.append("bow")   # Inventory now: ["sword", "shield", "potion", "bow"]

# Inserting an element at a specific index
inventory.insert(2, "map") # Inventory now: ["sword", "shield", "map", "potion", "bow"]

# Removing an element by value
inventory.erase("potion") # Inventory now: ["sword", "shield", "map", "bow"]

# Removing an element by index
inventory.remove(1)    # Inventory now: ["sword", "map", "bow"]

Common methods like append(), insert(), erase(), and remove() give you full control over the arrangement of your array’s elements, allowing your game logic to dynamically adjust to various conditions and player actions.

Accessing Array Elements

Accessing elements in an array is done using the index of the element. In Godot, indexes start at 0. Here are some examples:

# Accessing the first item
var first_item = inventory[0] # Returns "sword"

# Accessing the last item
var last_item = inventory[inventory.size()-1] # Returns "bow"

# Overwriting an element at a specific index
inventory[2] = "quiver" # Inventory now: ["sword", "map", "quiver"]

It is important to ensure that an element exists at an index before trying to access it to avoid runtime errors. This can be done with methods like size(), which returns the number of elements in the array.

Looping Through Arrays

Iterating over arrays is a fundamental practice that allows you to perform actions on every element. Godot provides intuitive syntax for loops:

# Using a 'for' loop to iterate through the array
for item in inventory:
    print(item) # Prints each item in the inventory array

# Using an indexed 'for' loop
for i in range(inventory.size()):
    print("Item %d: %s" % [i, inventory[i]]) # Prints each item with its index

Whether you’re applying effects to all enemies, updating UI elements, or just debugging, loops are an indispensable tool for array manipulation.

By mastering the basic operations shown in these examples, you start laying the foundation for more complex data handling in your Godot projects. In the next part, we’ll dive deeper into how arrays can be used to create richer gameplay experiences.

Leveraging arrays effectively can boost your game development to new heights. From level design to AI behavior, arrays are at the heart of countless functions. Let’s further unwrap the potential of arrays in Godot with more practical examples.

One of Godot’s strengths is working with multidimensional arrays, which can be used for creating grids or maps:

var grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # A 3x3 grid represented by a 2D array

# Accessing the second element in the first row
var value = grid[0][1] # Returns 2

For algorithmic generation or map manipulation purposes, multidimensional arrays are indispensable. You can create complex structures such as a tile map or level sections that players can navigate through.

Another vital concept in Godot is array duplication. When duplicating arrays, especially for instances where you need an original and a modified copy, you can use the duplicate() method to avoid modifying the original unintentionally:

# Shallow copy (references to inner arrays or objects are shared)
var shallow_copy = inventory.duplicate()

# Deep copy (creates a new instance of inner arrays or objects)
var deep_copy = inventory.duplicate(true)

Deep copying is particularly useful when you’re handling arrays of objects and you need a truly separate copy that does not affect the original objects when changed.

Godot’s arrays can also be sorted, which becomes incredibly useful while handling leaderboards or any list that needs to be ordered:

var scores = [23, 67, 12, 89, 34]
scores.sort() # The 'scores' array is now [12, 23, 34, 67, 89]

Additionally, working with arrays in Godot means having the ability to efficiently find elements:

# Find the index of an element (returns -1 if not found)
var index_of_34 = scores.find(34) # Returns 2

# Check if an array contains a certain element
var has_sword = inventory.has("sword") # Returns true

These methods streamline operations like checking for inventory items or retrieving a player’s score from a list without having to manually search through the array.

Furthermore, working with arrays isn’t just confined to built-in types. You can easily create arrays of custom objects, which unlocks a lot of flexibility when crafting your game’s logic:

# Define a custom class for game items
class GameItem extends Reference:
    var name = ""
    var power = 0
    
    func _init(_name, _power):
        name = _name
        power = _power

# Create an array of GameItem objects
var items = [
    GameItem.new("Excalibur", 50),
    GameItem.new("Aegis Shield", 30),
    GameItem.new("Healing Potion", 10)
]

# Access and use the custom objects
for item in items:
    print("Item %s has power %d" % [item.name, item.power])

Custom classes allow for complex types to be stored, opening the door to a more object-oriented approach in your game’s codebase, which is instrumental when managing unique items, characters, or abilities.

Wirh these practices and snippets, you’re now equipped to harness the array’s capabilities to the fullest within your Godot projects, forming solid building blocks towards crafting exceptional gaming experiences. As we continue to unravel the power of Godot 4 together, don’t hesitate to experiment with these examples and piece together your game world with confidence and creativity.

Continuing our journey with arrays in Godot, let’s now explore some more advanced functionality and code examples to further enhance your game development skill set.

Godot arrays come equipped with powerful filter and search capabilities which can be tremendously useful, especially for games with complex data sets:

# Filtering an array based on a condition
var high_scores = [80, 92, 55, 78, 99]
var passing_scores = high_scores.filter(func(score): return score > 75)
# The 'passing_scores' array will contain [80, 92, 78, 99]

Filtering is instrumental when dealing with inventories, enemy lists, or any collection where you need to separate elements by certain conditions.

Beyond filtering, mapping can transform each element in an array, another tool that can be especially powerful in managing game states:

# Applying a transformation to each element
var prices = [10, 20, 30]
var discount_prices = prices.map(func(price): return price * 0.9)
# The 'discount_prices' array will be [9, 18, 27]

This technique can be used, for example, to apply damage modifiers to a list of weapons or to calculate effect durations.

Combining arrays is also straightforward in Godot. You can quickly concatenate two or more arrays using the ‘+’ operator:

var array1 = [1, 2, 3]
var array2 = [4, 5, 6]
var combined_array = array1 + array2 # The result is [1, 2, 3, 4, 5, 6]

Combining arrays can be quite handy in scenarios where you might need to merge multiple lists of items, such as inventories from several chests or enemies from various spawn points.

When it comes to potent automation or procedural generation, leveraging ranges to populate arrays can save time and streamline your code:

# Creating a range of numbers and converting it to an array
var num_range = range(1, 11)
var number_array = Array(num_range) # The result is an array with numbers from 1 to 10

Ranges are ideal for initializing arrays with sequences like IDs, levels, or stat values without manually typing each entry.

In many RPG or strategy games, handling player attributes often involves arrays of dictionaries. Consider the example where each dictionary holds different player stats and you pack them into an array:

# An array of dictionaries with player attributes
var players = [
    {'name': 'Archer', 'hp': 100, 'mp': 50},
    {'name': 'Mage', 'hp': 60, 'mp': 120},
    {'name': 'Warrior', 'hp': 150, 'mp': 30}
]

# Iterating over the dictionaries to modify attributes
for player in players:
    if player['name'] == 'Mage':
        player['mp'] += 20 # Boost the Mage's MP

Whether it’s player stats, enemy AI states, or game level properties, arrays of dictionaries allow for organized and complex data manipulation.

Lastly, Godot’s array methods aren’t limited to the examples shown above. You have a plethora of built-in methods at your disposal, such as:

# True if the array is empty
var is_empty = inventory.empty()

# The current size of the array
var inventory_size = inventory.size()

# Reversing the array's order
inventory.reverse() # If inventory was ["sword", "map", "quiver"], it's now ["quiver", "map", "sword"]

With these advanced tools and techniques, your capability to create, manage, and manipulate arrays within Godot is greatly amplified. The real challenge and excitement lie in integrating these examples into your gaming project, creating tailored interactions, and orchestrating gameplay elements that genuinely engage your audience. Push the boundaries of your imagination, apply these concepts, and watch as your game worlds come to vibrant life!

Continuing Your Game Development Journey

Armed with a robust understanding of arrays in Godot, you’re now ready to take your game development skills to the next level. To keep the momentum going and to delve even deeper into the world of game creation, we invite you to explore our Godot Game Development Mini-Degree. This comprehensive course collection covers an array of topics from 2D and 3D game development to in-depth GDScript programming, ensuring you’re well-equipped to tackle any project that ignites your imagination.

Whether you’re a seasoned developer or just starting, our flexible, project-based courses provide practical knowledge that transcends the basics. You’ll find yourself creating complete games across various genres and enhancing your portfolio with our curated content available to access anytime, anywhere. Don’t limit your potential – your next step in mastering Godot and bringing your creative visions to life could begin with us at Zenva.

For those of you seeking to broaden your Godot expertise or to start unraveling its vast capabilities, our curated selection of Godot courses awaits to guide you through this exciting path. Join us at Zenva Academy and turn your passion for game development into an adventure of endless learning and discovery!

Conclusion

Conquering arrays in Godot marks a significant milestone in your game development journey. You’ve unlocked just one of the many doors leading to the rich and diverse universe of game creation. At Zenva, we believe in fostering your growth as a game developer by providing hands-on experience and the expertise needed to bring remarkable games to life. Our Godot Game Development Mini-Degree is a testament to our commitment to your learning journey, offering you the tools and community support to thrive in this dynamic industry.

As you continue to build, experiment, and learn, remember that each project hones your skills and takes you one step closer to mastery. With arrays now added to your scripting arsenal, imagine the realms you can craft, the stories you can weave, and the gameplay experiences you can curate. Let your creativity run wild and let Zenva be the wind beneath your wings as you soar into the exhilarating world of game development.

FREE COURSES
Python Blog Image

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