c# - 为什么按下按钮时我的方法没有全部运行?
问题描述
我正在尝试编写一种方法,允许我在按下按钮时购买升级。然而,往往会发生的是,一旦我按下按钮,该buyShiny()
方法只完全运行一次。之后它仍然会做mainScript.coins -= coins
,但没有别的。
代码可靠运行的唯一方法是,如果我为每次升级编写相同的代码。虽然这行得通,但我试图尽可能少地使用线条。
有问题的代码:
public void buyUpgrade(int level, int maxLevel, Text levelTxt, double cost, double costScale, double affectedValue,
double UpGScale, Text PriceTxt)
{
if (level >= maxLevel)
{
level = maxLevel;
}
else if (level < maxLevel)
{
mainScript.coins -= cost;
affectedValue *= UpGScale;
cost *= costScale;
PriceTxt.text = "Research\n" + shinyShellsCost.ToString("F2");
level++;
levelTxt.text = level + "x";
}
}
public void buyShiny()
{
if(mainScript.coins >= shinyShellsCost)
{
buyUpgrade(shinyShellsLvl, shinyShellsMaxLvl, shinyShellsLvlTxt, shinyShellsCost, 1.06, mainScript.shellPrice, 1.1, shinyShellsPriceToReschTxt);
}
}
工作代码:
public void buyShinyShell()
{
if(mainScript.coins >= shinyShellsCost)
{
if(shinyShellsLvl >= shinyShellsMaxLvl)
{
shinyShellsLvl = shinyShellsMaxLvl;
}
else if(shinyShellsLvl < shinyShellsMaxLvl)
{
mainScript.coins -= shinyShellsCost;
mainScript.shellPrice *= 1.1;
shinyShellsCost *= 1.06;
shinyShellsPriceToReschTxt.text = "Research\n" + shinyShellsCost.ToString("F2");
shinyShellsLvl++;
shinyShellsLvlTxt.text = shinyShellsLvl + "x";
}
}
}
解决方案
我猜not working
你指的是你的相应字段没有被改变。
您正在传递值类型 ( int
, double
),因此您对方法内的参数所做的任何更改都不会影响您类中的实际字段!外面的任何东西都不会知道方法内部发生了什么,所以你总是再次传递相同的值 - >似乎什么都没有发生。
您的第二个版本有效,因为您在那里直接操作类的实际字段。
为避免这种情况,您可以对ref
要在方法中更改的每个参数使用关键字,例如
public void buyUpgrade(ref int level, int maxLevel, Text levelTxt, ref double cost, double costScale, ref double affectedValue, double UpGScale, Text PriceTxt)
{
if (level >= maxLevel)
{
level = maxLevel;
}
else if (level < maxLevel)
{
mainScript.coins -= cost;
affectedValue *= UpGScale;
cost *= costScale;
PriceTxt.text = "Research\n" + shinyShellsCost.ToString("F2");
level++;
levelTxt.text = level + "x";
}
}
public void buyShiny()
{
if(mainScript.coins >= shinyShellsCost)
{
buyUpgrade(ref shinyShellsLvl, shinyShellsMaxLvl, shinyShellsLvlTxt, ref shinyShellsCost, 1.06, ref mainScript.shellPrice, 1.1, shinyShellsPriceToReschTxt);
}
}
现在您强制将这些传递的值视为引用,并将更新您通过ref
推荐阅读
- git - 如何通过 MR 自动更新 git 中的 CHANGELOG
- python - 运行张量流模型时如何隐藏终端消息?
- eclipse - Eclipse - 使用超链接功能而无需分步执行
- huawei-mobile-services - 华为应用市场。我的应用程序如何在中国大陆市场发布?
- java - Android 应用程序中的 BLE 错误:错误:bta_gattc_utils.cc(434)] bta_gattc_mark_bg_conn 无法找到 bg 连接掩码
- reactjs - 在反应中提交表单后,我从我的 api(express) 获得结果,但页面抛出错误无法读取未定义的属性“长度”
- flutter - 当设备在 Flutter 中解锁时如何运行我的应用程序
- amazon-web-services - 根据数字顺序从 DynamoDB 获取数据
- r - Shiny App的变化不停
- c++ - 取消引用指针如何更改此代码段中的值?