Unity3D代码重复过多

时间:2015-12-29 21:09:49

标签: c# unity3d unityscript

如果你有足够的黄金,那么你需要摇滚,如果你有足够的摇滚,那么你需要足够的黄金,但是如果你有两个,那么你可以“升级”。但如果你得到了两者,那么它就会回到你需要的黄金。

    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!";
        }
    }

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?首先要看用户是否有足够的黄金和岩石,然后进行检查 我已将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种可能性:如果用户只有足够的岩石,如果用户只有足够的金币,如果用户有足够的金币,如果用户没有足够的金币任何