错误的数字将int转换为字符串c#

时间:2019-02-22 10:05:38

标签: c# unity3d unity-ui

在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等。

3 个答案:

答案 0 :(得分:0)

您不必在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);
}

答案 1 :(得分:0)

最好将转换代码写入触发器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); 
}

`

答案 2 :(得分:0)

问题不在转换中,触发器工作了两次。在禁用硬币并将其添加到硬币计数器之前,需要检查硬币是否已启用。例如:

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