簡體   English   中英

錯誤的數字將int轉換為字符串c#

[英]Wrong number converting int to string c#

在2D Unity游戲中,我有簡單的硬幣計數器。 但是,將一枚硬幣算作2。我認為這是因為將int轉換為字符串錯誤。

public GameObject coin; // Gameobject with coin
public Text CoinCounter; // Text with counter that shows in game
private float TotalCounter = 0; // Float for counting total amount of picked up coins

{
   TotalCounter = Convert.ToInt32((CoinCounter.text)); // Converting text counter to Numbers
}

private void Update()
{

    TotalCounter = Convert.ToInt32((CoinCounter.text)); // Updating Counter evry frame update 
    Debug.Log(TotalCounter); // Showing Counter  in Console 
}

private void OnTriggerEnter2D(Collider2D collision)
{
    TotalCounter = (TotalCounter + 1); // adding 1 to total amount when player touching coin 
    CoinCounter.text = TotalCounter.ToString(); // Converting to Text, and showing up in UI





    coin.SetActive(false); // Hiding coin


}

因此,在“調試日志”中,它顯示正確的“總數”,但在UI中,它顯示了錯誤的數字。 例如,當“總金額”為1時,它將顯示2等。

您不必在Update執行此操作,而僅在實際更改時才需要執行此操作。

您正在尋找的方法可能是int.TryParse

您應該將int用作金額(除非以后會有1.5硬幣這樣的值)

比起每次代碼與任何東西沖突都執行代碼。 您只應與硬幣碰撞。 使用標簽或與您的案例中的參考值進行比較

public GameObject Coin; // Gameobject with coin
public Text CoinCounter; // Text with counter that shows in game
private int _totalCounter = 0; // Int for counting total amount of picked up coins

// I guess it's supposed to be Start here
void Start()
{
   // Converting text counter to Numbers
   int.TryParse(CoinCounter.text, out _totalCounter); 
}

private void OnTriggerEnter2D(Collider2D collision)
{
    if(collision.gameObject != Coin) return;

    // later this should probably rather be
    //if(collision.gameObject.tag != "Coin") return

    _totalCounter += 1; // adding 1 to total amount when player touching coin 
    CoinCounter.text = _totalCounter.ToString(); // Converting to Text, and showing up in UI

    Coin.SetActive(false); // Hiding coin

    // later this should probably rather be
    //collision.gameObject.SetActive(false);
}

最好將轉換器代碼寫入觸發器void中,然后再進行檢查; 由於更新功能,可能會發生這種情況,請嘗試這樣,然后再次檢查:

public GameObject coin;
public Text CoinCounter;
private float TotalCounter = 0; 
private void Update()
{}
private void OnTriggerEnter2D(Collider2D collision)
{
    TotalCounter = (TotalCounter + 1); 
    Debug.Log(TotalCounter); 
    CoinCounter.text = TotalCounter.ToString(); 
    Debug.Log(CoinCounter.text);
    coin.SetActive(false); 
}

`

問題不在轉換中,觸發器工作了兩次。 在禁用硬幣並將其添加到硬幣計數器之前,需要檢查硬幣是否已啟用。 例如:

 if (coin.activeSelf)
  {
      coin.SetActive(false);

      Debug.Log("Object is not active ");

      TotalCounter += 1;
      Debug.Log("Total Counter + :" + TotalCounter);
      CoinCounter.text = TotalCounter.ToString();
      Debug.Log("Text after +:" + CoinCounter.text);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM