Collider trigger two times, even if it's not active.
I have simple coin counter, in 2d Unity game. But It's count one coin as 2. If we look in to logs, we cant see that they work twice, when it's even not enabled.
public GameObject coin;
public Text CoinCounter;
private int TotalCounter = 0;
public BoxCollider2D collider;
// Start is called before the first frame update
void Start()
{
int.TryParse(CoinCounter.text, out TotalCounter);
Debug.Log("Counter on Start :" + TotalCounter);
Debug.Log("Text o");
}
private void Update()
{
TotalCounter = Convert.ToInt32((CoinCounter.text));
}
private void OnTriggerEnter2D(Collider2D collision)
{
collider.isTrigger = false;
if ((collider.isTrigger) == false)
{
Debug.Log("Collider Is not Trigger");
}else
{
Debug.Log("Collider is still trigger");
}
Debug.Log("Trigger Entered");
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);
}
}
![alt text][1]
[1]: /storage/temp/133581-logs.png
Answer by AaronBacon · Feb 22, 2019 at 06:36 PM
The Unity OnTriggerEnter2D can be a bit buggy and occasionally run twice, though you may want to check you haven't put multiple trigger colliders on either the player or the coin, as it will be running for each collision. A simple Workaround if that's not it would be to check if the coin is enabled before disabling it and adding to the coin counter. Eg:
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);
}
Another thing I would say is you may want to use Tags in the editor to make sure the player can differentiate between coins and other trigger objects. Assign the "Coin" tag to the coin, then do something like:
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Coin"))
{
// Run Code if its a coin
}
then make the coin object a Prefab by dragging it into the file explorer in the editor, so you can simply drag a completed coin object into the scene.