Reputation: 8125
I'm writing a game that involves cargo, and I plan to have a large number of cargo types. Currently I have a Cargo
class, and a ship carrying cargo has an array of the Cargo
s it is holding.
I'd really rather not have each ship with a bunch of objects when all I really want to know is how much of which cargoes each ship has. Especially when these ships will be created and discarded a lot.
I'm sure the thing I'm looking for is so basic I'll look dumb for even asking, but I know there's something similar to an array that holds an object and a related value. I want to use that to reference the Cargo
type from the static array, and hold the quantity.
What's it called? How would I use it (ie what are common functions used for it)? Some code snippets and terminology would be ideal.
Upvotes: 0
Views: 124
Reputation: 29949
You are probably looking for the Dictionary class. It's similar to arrays (which use integer indexes) or objects (which can be used as string based, associative arrays). A Dictionary uses objects as unique keys that get mapped to a single value.
I think you don't need one though. A global variable is rarely a good idea. I wouldn't unnecessarily complicate this and just let each ship handle it's own cargo, maybe by using a quantity as AaronLS suggested. But don't worry too much about performance here, even if you create and destroy thousands of ships each frame, rendering them will take significantly more time than the handling of arrays.
Anyway, here's how you use a dictionary and some things to consider. It doesn't have much special methods, it's used almost like an array.
var dict = new Dictionary();
var key:MyClass = new MyClass(); // a key can be of any class
dict[key] = "foo"; // set a value
trace( dict[key] ); // traces: foo
dict[key] = null; // set value to null, key is still there. It won't get garbage collected!
delete dict[key]; // remove the key
Consider using new Dictionary(true) to avoid the garbage collection issue.
Upvotes: 1
Reputation: 38367
Just make your cargo class contain a Quantity property.
Or you could have a CargoType class, which contains information about the type of Cargo(i.e. whether its some food, or money, or guns). Then you Cargo class would have a CargoType property and a Quantity property.
This way your array for the ship's cargo would only have a Cargo of each type and the Quantity property is used to indicate how many.
Upvotes: 3