Dictionary to Stack Class Types Together

2019-08-29 00:41发布

Enemy classes involved:

public abstract Enemy : MonoBehaviour {}

public class A : Enemy {}

public class B : Enemy {}

I have a dictionary. I want make the dictionary contain a stack for every type of Enemy.

    public class Test : MonoBehaviour
    {
       // prefabs
       public GameObject a, b;

       public Dictionary<Enemy, Stack> eDictionary; 

       void Start()
       {
          eDictionary = new Dictionary<Enemy, Stack>(); 
          Fill(a, 10);
          Fill(b, 10);
       }
    }

How I make the stack and keys.

public void Fill(Enemy e, int howMany)
{
   Stack s = new Stack();
   for(int I = 0; I < howMany; I++)
   {
      GameObject g = MonoBehavior.Instantiate(e.gameObject) as GameObject;
      s.Push(g);
   }

  eDictionary.Add(e, s)
}

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?

When I go into the generalized enemy classes A and B and try to add that enemy to the corresponding stack due to its key, I get key not matching error. I do this when I pop the Enemies out of the stack then when I am done with them I want to push them into the dictionary's stack (it fails at that point).

1条回答
放荡不羁爱自由
2楼-- · 2019-08-29 01:14

I think the issue might be to do with the key you're using.

When you're adding the stack to the Dictionary, you're giving it a key of an instance of enemy. So even if you reference that dictionary with the same type later on, it will be a different instance so it won't match.

One solution is to use the name of the class, as the key, rather than the object itself.

See this answer: https://stackoverflow.com/a/179711/1514883

查看更多
登录 后发表回答