Using Single and Multi-Dimensional Arrays in C# and Unity3D

Updated on May 28, 2019
beagrie profile image

John is a fervent writer, gamer, and guitar lover. Former automatic-transmission repairer, current welder and hobbyist game developer.

An array is a collection of data of a particular type that can be accessed using an index. It is particularly useful for storing information of a particular data type when you don’t necessarily know the amount of information you will need before-hand. For example, say you wanted to store a collection of integers. You could dedicate lines and lines of code to declaring each integer, giving each one a unique identifier that would allow you to access it at a later time. Or you could have a single array of integers and access each of your integers by simply passing an index value. Far more efficient, much easier to manipulate.

So let’s go over how to declare, assign variables to, and use an array in C#, and how this can translate to the Unity3D environment. For your convenience, I've also included a video version of this article below.

Using 1 and 2D Arrays in Unity3D / C#

Declaration

In order to declare an array, you simply state the data type you want followed by square brackets, and finally the identifier you want this array to go by. Like so;

integer[] array;

You may want to make your array publicly accessible, in which case you would qualify your declaration with a “public”, or you may want to ensure it remains inaccessible publicly, in which case you would qualify the declaration with “private”.

Initialization

It’s not enough to simply declare an array, however. You have to initialise it. As someone who learned to code largely through looking at examples online and watching YouTube tutorials, it does seem that failing to properly initialise arrays is one of the more common mistakes that beginners make.

So, to initialise your array, you need set it as a new instance of your data type array with a specified size. You can do this with your initial declaration or later in your code. The latter is useful for situations where you need the array to be accessible class-wise (so you need it declared at the top of your code), but you don’t know how large it needs to be until you start running your code. So, to initialise an array of integers with a size of six, you would type;

public integer[] array = new integer[6];

Or if you wanted your declaration and initialisation separate...

private int[] array;

public void SomeFunction () {

    array = new integer[6];

}

You can also declare, initialise, and set your array at the same time by setting the values on declaration. The size of the array will be inherently determined by the number of values you put in it. For example...

private int[] array = new int[] { 9, 4, 7, 1, 3, 6 };

...will give us an array of ints that is six long, and will already have the values set.

Setting Data

Once you have your array declared and initialised, and assuming you didn't assign variables at declaration as show above, it’s time to enter data into it. This is done very simply by passing an index into your array and then accessing it like an other variable. So, if we wanted to set the first item in the array to 9, we would type;

array[0] = 9;

You’ll notice we used 0, not 1, as our index value. Array indexes start at zero, which is important when accessing the last index of an array; you would subtract one from the length of the array in order to get the last item in that array. For example, to set the last item of our array to 6, you would do this;

array[array.Length - 1] = 6;

Looping Through the Array

Using our Length variable, we can loop through our array and set or access each of our items in just a few lines of code. The following snippet loops through all items in the array and sets their value to the same as their index, and then prints that value to the log.

for (int i = 0; i < array.Length; i++) {
 
    array[i] = i;
    Debug.Log (i.ToString());
 
}

Within the syntax of the for command you are creating an integer named “i”, declaring that the for loop will run while i is less than the length of the array, and that i will increment by one with each iteration of the loop. Notice we do not need to subtract one from array.Length. This is because we are looping while i is less than the length. Which will be true until i equals the length, so we will not go beyond the range of the array.

You can also loop through your array without using the Length variable by using the “foreach” command. In order to achieve the same results as above in this manner, you would type;

int count = 0;
foreach (int integer in array) {
 
    integer = count;
    Debug.Log(integer);
    count++;
}

As you can see, the syntax of the loop itself is more simplified. We simply declare our data type (int) and give it an identifier (integer) and then specify the array we are going to loop through (array). However the lack of an inherent incremental value means that we have to create and increment our own, as we did with the “count” variable.

2D Arrays

A two dimensional array can be thought of like a grid, or a list of arrays. You declare in the same way as a single dimensional array, but with a comma to denote that this array has more than one dimension.

public int array [,] = new int[,];

It is perhaps easiest to visualise a two dimensional array when setting the variables at declaration like so;

public int array [,] = new int[,]	{ 0, 5, 1 },
									{ 8, 2, 9 },
									{ 4, 6, 7 }

As you can see, the multidimensional array can be looked at as a two dimensional grid, or a list of single dimensional arrays, each of which is three in length. In order to get or set the value of an array position, you simply pass in the horizontal and vertical index, similar to a grid or spreadsheet. So if we wanted to print the lower right hand variable to the console, we would type;

Debug.Log(array[2, 2].ToString());

Remembering that the indexes start at zero so the maximum index is the length (3 in this case) minus one.

Using Arrays in Unity

Unity provides an automatic GUI solution to editing arrays in certain contexts through the Unity Inspector. There are two ways to get an array to be displayed in the inspector, you can either make it public (as shown above), or you can serialise it. This is how you would make a declaration serialised;

[SerializeField] private int[] array;
Making an array public or serialised in your code will allow you to edit in the Unity inspector.
Making an array public or serialised in your code will allow you to edit in the Unity inspector. | Source

Whether public or serialized, arrays that are displayed in the inspector are automatically initialised, so you do not need to set the size and content of the array in your code, though you can if you wish. Having an array public isn’t exactly best practice, however, so it would be better to get into the habit of having your arrays private (and serialized if you need to edit in the inspector) and write a public function for modifying or extracting information from the array. This also allows you to keep complete control over how information going in or out of the array is handled.

If, for whatever reason, you need your array to be public, and that array is going to have a LOT of items (thousands or more), you do NOT want it to show up in the inspector, as it will cause Unity to hang for a long time and probably crash. In such a situation, you can keep your array out of the inspector with the following qualifier;

[HideInInspector] public int[] array;

And, remember, these arrays would need initialising in your code.

Custom Class Arrays

Arrays can be made using a custom class as a data type by initialising in exactly the same way as shown above. The only difference is that if you want your array of custom classes to be shown in the inspector, you will need to make the class serialise. You do that by putting;

[System.Serializable]

Above your class. So a complete script for creating an array of a custom class data type might look like this;

using System;
using System.Collections.Generic;
using UnityEngine;

public class MyClass {

	[SerializeField] private SubClass[] myArray;

	public void SetValue (int index, SubClass subClass) {
	
		// Perform any validation checks here.
		myArray[index] = subClass;

	}

	public SubClass GetValue (int index) {

		// Perform any validation checks here.
		return myArray[index];

	}

}

[System.Serializable]
public class SubClass {

	public int number;
	public string text;

}

This would create an array of “SubClass”’s, which for now just hold some arbitrary information for demonstration purposes, that is visible and modifiable from the Unity inspector, but which would need pass through the SetValue and GetValue functions in order to manipulate the data in that array.

Source

And that’s the end of this brief tutorial on how to initialise and use arrays in C# and Unity3D. I hope you found this useful.

Do you feel like you understand the basics of arrays in C# and Unity3D?

See results

© 2019 John Bullock

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)