unity3d - 将一个变量的值设置为另一个变量的值
问题描述
我会给你一个我想要完成的例子。
使用 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
我知道它可以完成,但需要一些语法帮助,任何输入表示赞赏
解决方案
如果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]++;
}
推荐阅读
- r - 将 reactiveValues 数据框传递给反应式表达式
- julia - LoadError:PyCall.PyError ("\$(Expr(:escape, :(ccall(#= /home/omkar/.julia/packages/PyCall/ttONZ/src/pyfncall.jl:44 =# @pysym(:PyObject_Call)
- git - Vscode 使用 git 在服务器上工作(php 开发)
- javascript - 我无法让我的任何 JSLink 工作。我究竟做错了什么
- python-3.7 - Python 教程中的 NoReverseMatch 错误
- asp.net-core - .net core web api上传文件失败,请求错误
- unit-testing - 在 BDD 中测试副作用
- javascript - Three.js 动画混合器不播放?
- arrays - 如何找到多个数组中的最大元素值?
- jquery - JW Player - 禁用快进在 Microsoft Edge/IE11/Safari 中不起作用