一起堆栈类的字典 [英] Dictionary to Stack Class Types Together

查看:135
本文介绍了一起堆栈类的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public abstract敌人:MonoBehaviour {} 

public class A:敌人{}

public class B:Enemy {}

我有一个字典。我想让字典包含每种类型的敌人的堆栈。

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

public Dictionary< Enemy,Stack> eDictionary;

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

我如何制作堆栈和密钥。

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

eDictionary.Add(e,s)
}

主要的问题是:如何使用A类的敌人与1键一起使用键?



当我进入广义的敌人类A和B,并尝试将该敌人添加到相应的堆栈由于其键,我得到键不匹配的错误。我这样做,当我弹出敌人从堆栈然后当我完成他们我想把它们推入字典的堆栈(在那里失败)。

解决方案

我认为问题可能与您使用的密钥有关。



将堆栈添加到字典,你给它一个敌人的一个关键。所以即使稍后引用相同类型的字典,它将是一个不同的实例,因此它将不匹配。



一个解决方案是使用该类作为关键,而不是对象本身。



看到这个答案:
https://stackoverflow.com/a/179711/1514883


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).

解决方案

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

这篇关于一起堆栈类的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆