- Home /
2D C# destroy a GameObject on collision
i am new to unity and C# and i am trying to make my 1st game. my game is a cube that slides along the ground and if u crash into a box the game restarts and it adds 1 to your score. if you get to the finish line you will go to the next level.
i have the cube moving but using 2D C# code i cant get the cube to destroy when it crashes into the box.i know there is probably an easy way to do this! can anyone help thanks!
Answer by bahmrockk · Mar 09, 2014 at 08:18 PM
Hey,
To figure out if you hit something, you can use:
void OnCollisionEnter2D(Collision2D objectYouCollidedWith) { your_code}
and destruction of an object is taken quite literal: just call
Destroy(ObjectToBeDestroyed)
Now you can just add the Destroy(myCube) into the collision or handle it from the outside, depending on which way you want to go.
Answer by Stavros-Dimou · Oct 07, 2016 at 10:03 AM
Finally!!! I've been trying to get a 2d object to be destroyed when I shoot it in the 2d game I'm making for like 6 hours, watching different tutorials online again and again, reading stuff at forums and stuff, and everyone everywhere always said about OnCollisionEnter, nobody even reffered of OnCollisionEnter2D existing!
And well, being a newcomer I didn't knew there were different collision events for 2d and 3d games, yet everyone on all tutorials online assume only people who want to make 3d games will ever watch their tutorials, and they don't even talk about the existence of seperate events, methods etc for 2d games. It was driving me crazy, like "Why does it work for all these people and not for me ?", it got me frustrated.
Have a nice day and be well sir.