【问题标题】:Unity - Dealing with multiple arrays and understanding loopsUnity - 处理多个数组并理解循环
【发布时间】:2020-10-30 19:20:42
【问题描述】:

所以我很难理解多个数组和循环是如何工作的。例如,在一个游戏中,您拥有交易功能并创建了这样的方法:

public void TradeItems(string[] giveItemKey, int[] giveAmount, string[] takeItemKey, int[] takeAmount)
{

}

您可以调用该方法以用更少的物品换取更多物品,反之亦然。例如,你给 3 双匕首和 4 靴子换 2 护甲。

TradeItems(new string[] { "Double Dagger", "Boots" }, new int[] { 3,4}, new string[] {"Armor" }, new int[] {2 });

那么基于那个方法,你会怎么做呢?会是这样吗?

public void TradeItems(string[] giveItemKey, int[] giveAmount, string[] takeItemKey, int[] takeAmount)
{
  if (HasItemsToTrade())
    {
        for (int i = 0; i < giveItemKey.Length; i++)
        {
            RemoveItems(giveItemKey[i], giveAmount[i]);
        }
        for (int i = 0; i < takeItemKey.Length; i++)
        {
            AddItems(takeItemKey[i], takeAmount[i]);
        }
    }
    else
    {
        Debug.Log("You don't have required items to trade");
    }

}

还要注意 giveItemKey 数组和 takeItemKey 数组可以有相等或不等的长度等。

感谢我能获得的有关这些方面的任何帮助和知识。

【问题讨论】:

  • 您是否正在为void TradeItems() 函数找到更好的解决方案?
  • 是的,可能是一个更干净或更简单的结构

标签: c# arrays for-loop unity3d foreach


【解决方案1】:

一般来说,我宁愿使用Dictionary,而不是最终大小匹配的两个单独的项目集合..

public void TradeItems(Dictionary<string, int> give, Dictionary<string int> take)
{
    if (HasItemsToTrade(give))
    {
        foreach(var givePair in give) 
        {
            RemoveItems(givePair.Key, givePair.Value);
        }

        foreach(var takePair in take)
        {
            AddItems(takePair.Key, takePair.Value);
        }
    }
    else
    {
        Debug.Log("You don't have required items to trade");
    }
}

所以您的HasItmesToTrade 可能会遍历give 中的条目并检查它们是否在您的库存中,例如

private bool HasItemsToTrade(Dictionary<string, int> give)
{
    foreach(var kvp in give)
    {
        if(!inventory.ContainsKey(kvp.Key)) return false;

        if(inventory[kvp.Key] < kvp.Value) return false;
    }

    return true;
}

所以你宁愿这样称呼它

TradeItems(new Dictionary<string, int> { {"Double Dagger", 3}, {"Boots", 4} }, new Dictionary<string, int>{ {"Armor", 2 } });

【讨论】:

  • 肯定更简洁的代码。看看它是否适用于我的 scriptableobject 项目
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-10
  • 2017-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
相关资源
最近更新 更多