Dictionary to Stack Class Types Together

五迷三道 提交于 2019-12-13 20:49:00

问题


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:


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



来源:https://stackoverflow.com/questions/20110376/dictionary-to-stack-class-types-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!