将 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);
  }