- Home /
Dictionary Keys to Stack Enemy Types
public abstract class Enemy : MonoBehaviour {}
Then
public class A : Enemy {}
public class B : Enemy {}
Then I want to make a key to represent instantiated objects of those two classes.
public class Test : MonoBehaviour
{
// prefabs
public GameObject a, b;
public Dictionary<Enemy, Stack> eDictionary;
}
I do plan to store instantiated gameObjects into the dictionary.
How do I make the keys?
How do I store the gameObjects into the dictionary on their void Awake() functions?
The main problem is: How do I make the keys in such a way that the Enemies of type A stack together with 1 key
Answer by Azrapse · Nov 20, 2013 at 02:04 PM
It can be done in several ways.
If you really require every Enemy to register themselves into the dictionary on Awake, then the dictionary must be accesible from the Awake method. For example a singleton or making eDictionary public and static. I would go for the singleton, with specific methods for adding and removing Enemies to and from the dictionary. But your needs might vary.
This is a proposal using a static class.
public static class EnemyStacks
{
static Dictionary<Type, Stack<Enemy>> eDictionary;
static EnemyStacks()
{
eDictionary = new Dictionary<Type, Stack<Enemy>>();
}
public static void Push<T>(T enemy) where T: Enemy
{
if(!eDictionary.ContainsKey(enemy.GetType())
{
eDictionary.Add(enemy.GetType(), new Stack<T>());
}
eDictionary[enemy.GetType()].Push(enemy);
}
public static Enemy Pop<T>() where T: Enemy
{
return eDictionary[typeof(T)].Pop();
}
}
Then in the respective enemy subclases
void Awake()
{
EnemyStacks.Push(this);
}
The problem is trying to group all the Enemies of type A into one stack. So a key would give you access to a stack of all the A enemies.
Your Awake code will make a key for n enemies.
Okay, I misunderstood (although I would swear your question didn't state the same in the last lines...) Now it's doing as you want.
That is a very good answer. I really like that you mentioned one of my favorite design patterns as well :)