首页 > 解决方案 > 为什么按下按钮时我的方法没有全部运行?

问题描述

我正在尝试编写一种方法,允许我在按下按钮时购买升级。然而,往往会发生的是,一旦我按下按钮,该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";
            }
        }
    }

标签: c#unity3dbuttonuibutton

解决方案


我猜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


推荐阅读