Sunday, May 15, 2011

Unity3d + C#: Using List and ArrayList array

Usually when creating an inventory, you would need to first create an array variable to store the content of the inventory. Using UnityScript (or JavaScript) you can do that by declaring an Array variable directly:
var inventoryArray : Array = new Array();


However to do the same thing in C#:
public Array inventoryArray = new Array();

That wouldn't work, instead it return you with an error saying:
error CS0246: The type or namespace name `Array' could not be found. Are you missing a using directive or an assembly reference?

And the error was pretty much self explanatory, that the "Array" doesn't exist in C#, instead it has ArrayList and List. But for the rest of the example, I'm gonna be using List (though it works the same as ArrayList), because I was having a hard time memorizing what type of information am I storing inside an ArrayList when I'm declaring a large number of them (3 to 5 can be messy enough for me) in a script; on the other hand, I felt more secure with List as I can check back on what type of List I'm using and what info I should and shouldn't add into it... more on that later...

To use the List array, you have to first use the namespace System.Collection.Generic, by adding it up above the script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic; // <-- add this line

Then declare a variable for it (public List variableName):
public List<int> inventory;
To actually start using it, as always you have to first declare the size or capacity of the array, because if you don't, Unity will either hang or crash after you click "Play", for some unknown freaking reason...

In the Start function:
inventory.Capacity = 9; // let's make it able to store 9 object inside...
To add something content into it:  
inventory.Add(2); // since this is a "int" array, you can only store another integer into it... anything else would return an error...

inventory.Add("this works!"); // for if your List array is a "string" array...
And then to clear up everything, I mean, delete all infos, turn the array size back to zero:  
inventory.Clear();

That was the part of the List method I love the most, because usually when I was using a normal array (int[], for int array; string[], for string array; bool[] for boolean array), there's such function as Clearing up and Adding stuff into the array... But I could be wrong, because I haven't use most of its features yet... which I'll, in the future.

More on what it could do: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

No comments: