Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Unity Scripting

You're reading from   Mastering Unity Scripting Learn advanced C# tips and techniques to make professional-grade games with Unity

Arrow left icon
Product type Paperback
Published in Jan 2015
Publisher
ISBN-13 9781784390655
Length 380 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Alan Thorn Alan Thorn
Author Profile Icon Alan Thorn
Alan Thorn
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Unity C# Refresher FREE CHAPTER 2. Debugging 3. Singletons, Statics, GameObjects, and the World 4. Event-driven Programming 5. Cameras, Rendering, and Scenes 6. Working with Mono 7. Artificial Intelligence 8. Customizing the Unity Editor 9. Working with Textures, Models, and 2D 10. Source Control and Other Tips Index

Arrays

Lists and sequences are everywhere in games. For this reason, you'll frequently need to keep track of lists of data of the same type: all enemies in the level, all weapons that have been collected, all power ups that could be collected, all spells and items in the inventory, and so on. One type of list is the array. Each item in the array is, essentially, a unit of information that has the potential to change during gameplay, and so a variable is suitable to store each item. However, it's useful to collect together all the related variables (all enemies, all weapons, and so on) into a single, linear, and traversable list structure. This is what an array achieves. In C#, there are two kinds of arrays: static and dynamic. Static arrays might hold a fixed and maximum number of possible entries in memory, decided in advance, and this capacity remains unchanged throughout program execution, even if you only need to store fewer items than the capacity. This means some slots or entries could be wasted. Dynamic arrays might grow and shrink in capacity, on demand, to accommodate exactly the number of items required. Static arrays typically perform better and faster, but dynamic arrays feel cleaner and avoid memory wastage. This chapter considers only static arrays, and dynamic arrays are considered later, as shown in the following code sample 1-4:

01 using UnityEngine;
02 using System.Collections;
03 
04 public class MyScriptFile : MonoBehaviour 
05 {
06     //Array of game objects in the scene
07     public GameObject[] MyObjects;
08 
09      // Use this for initialization
10      void Start ()
11      {
12       }
13 
14       // Update is called once per frame
15       void Update () 
16       {
17       }
18 }

In code sample 1-4, line 07 declares a completely empty array of GameObjects, named MyObjects. To create this, it uses the [] syntax after the data type GameObject to designate an array, that is, to signify that a list of GameObjects is being declared as opposed to a single GameObject. Here, the declared array will be a list of all objects in the scene. It begins empty, but you can use the Object Inspector in the Unity Editor to build the array manually by setting its maximum capacity and populating it with any objects you need. To do this, select the object to which the script is attached in the scene and type in a Size value for the My Objects field to specify the capacity of the array. This should be the total number of objects you want to hold. Then, simply drag-and-drop objects individually from the scene hierarchy panel into the array slots in the Object Inspector to populate the list with items, as shown here:

Arrays

Building arrays from the Unity Object Inspector

You can also build the array manually in code via the Start function instead of using the Object Inspector. This ensures that the array is constructed as the level begins. Either method works fine, as shown in the following code sample 1-5:

01 using UnityEngine;
02 using System.Collections;
03 
04 public class MyScriptFile : MonoBehaviour 
05 {
06     //Array of game objects in the scene
07     public GameObject[] MyObjects;
08 
09     // Use this for initialization
10     void Start ()
11     {
12          //Build the array manually in code
13          MyObjects = new GameObject[3];
14          //Scene must have a camera tagged as MainCamera
15          MyObjects[0] = Camera.main.gameObject; 

16       //Use GameObject.Find function to
17       //find objects in scene by name
18       MyObjects[1] = GameObject.Find("Cube"); 
19       MyObjects[2] = GameObject.Find("Cylinder"); 
20     }
21 
22     // Update is called once per frame
23     void Update ()
24     {
25     }
26 }

The following are the comments for code sample 1-5:

  • Line 10: The Start function is executed at level startup. Functions are considered in more depth later in this chapter.
  • Line 13: The new keyword is used to create a new array with a capacity of three. This means that the list can hold no more than three elements at any one time. By default, all elements are set to the starting value of null (meaning nothing). They are empty.
  • Line 15: Here, the first element in the array is set to the main camera object in the scene. Two important points should be noted here. First, elements in the array can be accessed using the array subscript operator []. Thus, the first element of MyObjects can be accessed with MyObjects[0]. Second, C# arrays are "zero indexed". This means the first element is always at position 0, the next is at 1, the next at 2, and so on. For the MyObjects three-element array, each element can be accessed with MyObjects[0], MyObjects[1], and MyObjects[2]. Notice that the last element is 2 and not 3.
  • Lines 18 and 19: Elements 1 and 2 of the MyObjects array are populated with objects using the function GameObject.Find. This searches the active scene for game objects with a specified name (case sensitive), inserting a reference to them at the specified element in the MyObjects array. If no object of a matching name is found, then null is inserted instead.

Tip

More information on arrays and their usage in C# can be found online at http://msdn.microsoft.com/en-GB/library/9b9dty7d.aspx.

You have been reading a chapter from
Mastering Unity Scripting
Published in: Jan 2015
Publisher:
ISBN-13: 9781784390655
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $24.99/month. Cancel anytime