繁体   English   中英

在 Unity3d 中,如果不对 if 语句进行硬编码,我的分数就不起作用

[英]In Unity3d my Score doesnt work without hardcoding the if Statement

所以我的问题是球员x位置=他达到的分数。 但我想在达到特定金额后关闭柜台。 我的问题是如果不对比较值进行硬编码,我就无法执行 If 语句。

//public text value for the Text
    public Text scoreText;
    //Takes the player Transform
    public Transform player;

    public int bossFightMeter = 2000;

    // Update is called once per frame
    void Update()
    {   //compares the postion on x with an value (check how to solv it without hard coding it)
        if (player.position.x < bossFightMeter) 
        {
            //The X postion of the player is converted to string and displayed on the Text output 
            scoreText.text = player.position.x.ToString("0");   //set to 0 so it counts in full numbers
        }
    }

如果我写

if(player.position.x < 2000)
{
   ...
}

然后它确实有效,但我不想像这样对其进行硬编码。

我实际上刚刚发现它不计数的原因是.ToString("0");。 但是如果我把它改成.ToString(); 那么分数不计入整数。 我该如何改变?

您的 bossFightMeter 变量设置为 public。 检查统一检查器的值是否为 2000。如果您已更改代码内部的值但未在检查器中更改,则代码将使用检查器的值。 您可以将该变量设为私有,或者始终在检查器中设置您想要的值,或者在 void start() 中设置它的值。

如果您仍想保持分数以整数计数,您可以在将它们分配给分数之前对数字进行四舍五入。

您可以使用Math.Round方法来分配三个参数:

  1. 要四舍五入的值。
  2. 值后要保留的小数位数。
  3. 您可以调用以使用AwayFromZero舍入的可选参数。 (除非舍入不明确,否则忽略,例如 1.5)

示例代码:

// Update is called once per frame
void Update()
{   
    //compares the postion on x with the bossFightMeter
    if (player.position.x < bossFightMeter) 
    {
        // The X postion of the player is rounded to the nearest full number
        var rounded = Math.Round(player.position.x, 0, MidpointRounding.AwayFromZero);

        // Set text to be the rounded number.
        scoreText.text = rounded.ToString();
    }
}

AwayFromZero 1.5 舍入到 2,没有AwayFromZero就不会发生。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM