Unity3D代码重复太多

本文关键字:太多 代码 Unity3D | 更新日期: 2023-09-27 18:28:34

我试图让你得到足够的黄金,那么你就需要岩石,如果你得到了足够的岩石,那么你需要足够的黄金。但如果两者都有,那么你可以"升级"。但如果你两者都有,那么它就会回到你需要的黄金。

    void Update()
    {
        if(enoughgold == true & enoughrocks == true)
        {
            Upgrade.text = "Upgrade to 2014!";
        }
        if(sellrocks.gold > 9999)
        {
            enoughgold = true;
        }
        else
        {
            enoughgold = false;
        }
        if(click.rock > 2999)
        {
            enoughrocks = true;
        }
        else
        {
            enoughrocks = false;
        }
        if(enoughgold == true)
        {
            Upgrade.text = "You need 3,000 Rocks!";
        }
        else
        {
            Upgrade.text = "You need 10,000 Gold!";
        }
        if (enoughrocks == true)
        {
            Upgrade.text = "You need 10,000 Gold!";
        }
        else
        {
            Upgrade.text = "You need 3,000 Rocks!";
        }
    }

Unity3D代码重复太多

这样的东西怎么样?您首先查看用户是否有足够的黄金和岩石,然后进行检查
我已经将if (enoughgold == true)简化为if (enoughgold),因为== true是冗余的。

void Update()
{
    enoughgold = sellrocks.gold > 9999;
    enoughrocks = click.rock > 2999;
    if (enoughgold && enoughrocks)
        Upgrade.text = "Upgrade to 2014!";
    else if (enoughgold && !enoughrocks)
        Upgrade.text = "You need 3,000 Rocks!";
    else if (!enoughgold && enoughrocks)
        Upgrade.text = "You need 10,000 Gold!";
    else if (!enoughgold && !enoughrocks)
        Upgrade.text = "You need 10,000 Gold and 3,000 Rocks!";
}

您还可以创建一个枚举来处理所有4种可能性:如果用户只有足够的岩石,如果用户只有充足的黄金,如果用户两者都足够,如果用户没有足够的黄金。