- Home /
OnCollisionEnter2D doesn't work every time.
I'm making a asteroids game and every time i shoot a asteroid, i want to gain 10 or 20 points. The way i set it up on the asteroid is:
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Shot")
{
Destroy(col.gameObject);
Destroy(gameObject);
if (childAsteroid != null)
{
for (int i = 0; i < spawnAmount; i++)
{
Instantiate(childAsteroid, transform.position, transform.rotation);
}
}
}
}
On the bullet:
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "smallAsteroid")
{
Gamemanager.points += 10;
}
else if (col.gameObject.tag == "mediumAsteroid")
{
Gamemanager.points += 20;
}
}
And in the gamemanager:
public class Gamemanager : MonoBehaviour
{
public static int points;
public Text text;
// Use this for initialization
private void Start()
{
}
// Update is called once per frame
public void Update()
{
text.text = "Points: " + points;
}
}
Sometimes i gain points and sometimes i don't... I can't figure out why.
Answer by MrSoad · Dec 08, 2014 at 09:12 PM
You are Destroying the bullet ("Shot") before it has run its collision code. One collision will always be processed before another, sometimes the Bullet collision is run first(and it works how you want) but sometimes the Asteroid collision is run first and this Destroys your Bullet so the Bullet collision script never runs.
To fix this add your score in the Asteroid collision script, and put your Destroy code at the very end of this script. Get rid of the code in your Bullet collision script that relates to the Asteroids (only!) completely.
If you are using the same script on all your asteroids then add a public Bool var Is_Medium to the script and set this up in on the script in the inspector window for each of the two prefabs. Now use this Bool to determine what score to add when this event occurs.
Your answer
Follow this Question
Related Questions
Object passes through collider even when isTrigger is turned off. 2 Answers
Collision point problem 1 Answer
What does it mean to be "grounded"? 0 Answers
Why can't I destroy this object!? 3 Answers
Best way to manually calculate collision between GameObjects and a Tilemap without using physics 1 Answer