首页 > 解决方案 > 将一个变量的值设置为另一个变量的值

问题描述

我会给你一个我想要完成的例子。

使用 twine2(我开始的地方),我可以通过直接引用其他变量来以编程方式设置和操作变量(我将为不熟悉 twine 的人解释一下语法)。

初始化并设置我的变量

  // data map is equivalent to dict
$Inv = (dm: potion, 0, bomb, 0, gold, 0);
  // array
$PossibleRewards =(a: potion, bomb, gold);
  // string
$Reward "";

然后

set $Reward to (shuffled... $PossibleReward's 1st);
set $Inv's $Reward to it +1;

所以它所做的只是简单地打乱 PossibleRewards 数组,选择第一个条目,然后将 Reward 字符串设置为所选内容,然后自动将 Inv 数据映射适当的条目增加一个。

当然你可以跳过字符串然后去

set $Inv's (shuffled... $PossibleReward's 1st to ot +1

我知道它可以完成,但需要一些语法帮助,任何输入表示赞赏

标签: unity3dsyntax

解决方案


如果PossibleRewards只是Dictionary.Keys值的副本,那么您可能不需要它。您可以使用Random该类使用字典的ElementAt方法(返回 a KeyValuePair)来获取字典中的随机项,将 设置Reward为该Value元素的 ,然后可以增加Value字典中该元素的 :

Random rnd = new Random(); // Note: you typically only need one instance of Random in a class

// Create a dictionary of rewards and quantity
Dictionary<string, int> inventory = new Dictionary<string, int> 
    {{"potion", 0}, {"bomb", 0}, {"gold", 0}};

// Grab the Key of a random item in the dictionary for the reward
string reward = inventory.ElementAt(rnd.Next(inventory.Count)).Key;

// Increment the value at that Key
inventory[reward]++;

否则,如果需要该列表(例如,如果Rewards是不同类的实例之间的共享列表),则可以基于该列表初始化单个库存字典。最简单的方法是使用System.Linq扩展方法,ToDictionary

private static readonly Random Random = new Random();
private static readonly List<string> Rewards = new List<string> {"potion", "bomb", "gold"};

private static void Main()
{
    // Initialize an inventory dictionary based on the shared list of rewards
    var inventory = Rewards.ToDictionary(key => key, value => 0);

    // Grab the Key of a random item in the dictionary for the reward
    var reward = inventory.ElementAt(Random.Next(inventory.Count)).Key;

    // Increment the value at that Key
    inventory[reward]++;
}

推荐阅读