簡體   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