Arrays are a collection of values/items stored together.
In GDScript, arrays can contain values of different data types.
var example = [] # an empty array
var anotherExample = [1, "hello", true] # an array with different data types
You are able to retrieve a single element from the array:
var example = [10, 20, 30]
var firstElement = example[0] # 10
var secondElement = example[1] # 20
var thirdElement = example[2] # 30
To get the length of an array, use the size
method:
var example = [ 1,2,3 ]
var length = example.size()
print(length) # 3
You can have arrays inside of arrays. These are called sub-arrays.
var subArray = [ [1,2], [9,10] ] # an empty array
# Get a value from the first subarray
var subarrayValueOne = subArray[0][0] # 1
var subarrayValueTwo = subArray[1][1] # 10
To push a value to either the front or back of an array, use the push method:
var example = [ 1,2,3 ] # an empty array
# Get a value from the first subarray
example.push_front(0) # example = [0,1,2,3]
example.push_back(4) # example = [0,1,2,3,4]
To pop a value out of an array, you can use the pop method:
var example = [ 1,2,3 ] # an empty array
# Get a value from the first subarray
example.pop_front() # example = [2,3]
example.pop_back() # example = [3]
There are a few ways to clear an array:
var example = [ 1,2,3 ]
example = []
resize
methodvar example = [ 1,2,3 ]
example.resize(0)
clear
methodvar example = [ 1,2,3 ]
example.clear()
In Godot, if you try to pass an array to another variable, an issue occurs.
The issue is that two variables will have access to the same array values.
var example = [ 1,2,3 ]
var anotherArray = example # anotherArray = [1,2,3]
anotherArray.push_front(4)
print(example) # [1,2,3,4]
To avoid this issue, you will need to implement either a deep copy or a shallow copy.
A shallow copy copies the array except for sub-arrays.
This means that all nested arrays and dictionaries will be shared with the original array.
A shallow copy uses the duplicate
method with the false value passed inside the parentheses.
var example = [ 1,2,3, [1,2] ]
var anotherArray = example.duplicate(false) # anotherArray = [1,2,3,[1,2]]
anotherArray.push_front(4)
print(example) # [1,2,3,[1,2]]
anotherArray[3][0] = 100
print(example) # [1,2,3,[100,2]]
print(anotherArray) # [1,2,3,[100,2],4]
A deep copy copies the array, including sub-arrays.
This means that all nested arrays and dictionaries will not be shared with the original array.
To do a deep copy, use the duplicate
method with the value true
passed inside the parentheses.
var example = [ 1,2,3, [1,2] ]
var anotherArray = example.duplicate(true) # anotherArray = [1,2,3,[1,2]]
anotherArray.push_front(4)
print(example) # [1,2,3,[1,2]]
anotherArray[3][0] = 100
print(example) # [1,2,3,[1,2]]
print(anotherArray) # [1,2,3,[100,2],4]
Arrays | Godot GDScript Tutorial | Ep 10 video & article by Godot Tutorials is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License .