Game Development Reference
In-Depth Information
17 Words[2]="car";
18 Words[3]="vehicle";
19 Words[4]="computers";
20
21 //add to dictionary with scores
22 foreach(string Word in Words)
23 WordDatabase.Add(Word, Word.Length);
24
25 //Pick word from list using key value
26 //Uses array syntax!
27 Debug.Log ("Score is: " +
WordDatabase["computers"].ToString()
);
28 }
29 }
The following are the comments for code sample 6-3:
•
Line 03
: As with the
List
class, you must include the
System.Collections.
Generic
namespace
•
Line 08
: Here, the dictionary is declared and created in one line; unlike the
List
class,
Dictionary
does not appear in the Unity Object Inspector
•
Lines 13-23
: The
Dictionary
class is populated using the
Add
method
•
Line 27
: Elements in the
Dictionary
class are accessed much like arrays,
except by specifying each element using its key data instead of an array index
More details on using
Dictionary
can be found in
Chapter 4
,
Event-driven Programming
, when considering event-driven
programming with an
EventManager
.
The Stack class
If you're making a card game where players should pick the top card from a deck,
if you need an undo history, if you're coding customized path finding, or if you're
creating a complex spell-casting system or even a Tower of a Hanoi puzzle game
you'll need a stack somewhere along the line. A stack is a special kind of list based
on the
Last in, first out
(
LIFO
) model. The concept is about stacking. You can push
items into the list, and these stack up one atop the other in a vertical tower, with the
most recently pushed item always at the top. Then, you can pop items from the top
of the stack (remove them from the array) one by one. The order in which you pop
items is always the inverse of the order in which they were pushed.