0

我有简单的硬币计数器,在 2d Unity 游戏中。但它把一枚硬币算作 2。我认为这是因为错误地将 int 转换为 string。

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

4

3 回答 3

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);
}
于 2019-02-22T10:22:23.913 回答
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); 
}

`

于 2019-02-22T10:30:33.253 回答
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);
  }
于 2019-02-23T07:58:20.060 回答