Randomising Item Drops
An introduction to using Arrays in Unity
In this article, you’ll start learning about effectively storing lists of data by using an Array, and how to retrieve set or random data from that Array.
Prelude
Now that we have a couple Items to drop, let’s see how we can store and access them effectively.
This is how we spawn an Item currently:
But, we have a lot more Item Drops. What we could do is assign an ID to each referenced power-up, and activate the corresponding logic:
Or not …, because Unity provides much cleaner and more effective ways to store lists of data. One way is to make use of an Array.
Array
An Array stores a sequential collection of values of the same type and we can use it to store lists of values in a single variable.
We declare an Array by saying what type of data will be stored in the Array, immediately closed by a square bracket, [ ]. We can store different types of data as long as they are of the same type. The size of the Array is set during the assignment.
There are different ways we can declare an Array:
A few examples:
GameObject.FindGameObjectsWithTag is a special built-in Unity function that takes a string parameter(tag) and returns an array of GameObjects using this tag.
Retrieving data from the Array
To retrieve data from the Array we first need to declare the Array name, followed by square brackets enclosing a integer value that’s called the index. The index indicates the element position in the Array. If we were to retrieve a specific element in the Array we simply have to declare its integer value (after having them manually assigned in the Inspector in our case).
myArray[index];
So if we’d like to retrieve a specific item drop, we could say the following (the order must match though):
To get the size of the Array we can use the following keyword:
Randomising the Index
Not only can we access an element by its index, since we have the ability to pass in an integer for now we might as well set the index to a random value ranging from the first element to the last element in the Array.
Conclusion
We’ve learned how to use an Array and how to randomise the index number. Now each time an entity is destroyed, a random item is dropped.
Note that there are different Array Types (javascript, C#, Built-in, …) and that there are other ways to store lists of data, for example by using a List, Arraylist or dictionaries and hash-tables. In time we’ll be examining the usage of these as well, but for the sake of this article it’ll suffice for now knowing how a basic Built-in Array works.
In the following article I’ll be introducing a new Weapon for the Player, the Triple Laser.