[英]How do I get properties for each object in the array?
我正在尝试写一个纸牌游戏,我有这个问题。
我有一个List<int> address 1 Player;
其中包含一组带参数的卡片。
我需要从这张表中提取每张卡的参数。
例如, List<int> address1Player
包含 id 为 1、2、3 的卡片。我需要找出List<int> adress1Player
中卡片的 colors 是什么。 Colors 存储在int
中。
颜色获取参数如下所示
public int PropertyColor(int adress){
return allProperties [adress].GetComponent<Plot> ().GetColor ();
}
如何确保我最终得到一个包含每张卡的 colors 的阵列?
List<int>
仅包含整数列表-在您的情况下为ID。 您想存储 colors 的数据结构(表面上,还有一些关于卡片的其他值),因此List
不是您想要的集合。 首先,让我们考虑一下我们的集合将持有的数据结构,然后我们将回到集合。
我们游戏中的卡片至少有两个属性:ID 和基于 integer 的颜色。 在 C# 中,我们编写类或结构来将属性的逻辑包分组到 object 中。 它看起来(很简单)是这样的:
public struct KorsunsCard
{
public int Id;
public int CardColor
}
现在,我们有一个“卡片”object,它具有我们可以检查和设置的属性,如下所示:
KorsunsCard greenCard = new KorsunsCard() { Id = 1, CardColor = 6 };
greenCard.CardColor = 5; // change the color to "5"
if (greenCard.Id == 2) { .. do some stuff }
然后,我们可以让方法返回整张卡片:
public KorsunsCard GetCardWithID(int Id)
{
KorsunsCard returnCard = ...
... we'll get to this part in a moment ...
return returnCard;
}
现在,关于那些 collections。 选择要使用的数据结构是 C# 的核心。 Collections 是对象的“组”——在我们的例子中是KorsunsCard
s。 每个集合都可以做好不同的事情 - List
可以通过“索引”(而不是 Id)访问卡片,遍历整个列表,对自己进行排序等。 Dictionary
用于通过键查找卡片,并且虽然它们可以遍历整个字典,但它们通常并不适用于此,因此语法涉及更多。 不难,只是不如List
容易。 您可能还需要一个HashSet
,一个只能有一个唯一项目的集合 - 但没有排序,就像字典一样。
我不能建议最好的解决方案,因为这取决于你的游戏规则(你的牌组总是有相同数量的牌吗?每种牌只有一张?用户是否从可用牌池中构建自己的牌组? ?)。
让我们从一些卡片开始:
KorsunsCard ace = new KorsunsCard() { Id = 1, Color = 1 };
KorsunsCard deuce = new KorsunsCard() { Id = 2, Color = 2 };
KorsunsCard trey = new KorsunsCard() { Id = 3, Color = 3 };
如果你想要一个List
,你可以声明它并向它添加一些值,如下所示:
List<KorsunsCard> myDeck = new List<KorsunsCard>();
myDeck.Add(ace);
myDeck.Add(deuce);
myDeck.Add(trey)
int deuceColor = deuce.Color; // deuce's color
return myDeck[0]; // ace, but be aware the list can be shuffled/sorted!
foreach (KorsunsCard kc in myDeck) // iterate on the whole deck
{
kc.Color = 4; // set the entire decks color to 4 , one at a time
}
通用集合类型Dictionary
、 HashSet
、 Queue
、 Stack
可能都与您的游戏相关,具体取决于您通常如何与套牌和游戏规则进行交互。 希望我已经从List
中为您提供了足够的信息,您可以 go 并阅读这些其他集合类型并使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.