- Home /
How to count from 2nd collision
Hi, i want to kill my player if it touch floor after landing on it, but problem is, that it's spawning on this floor, then jump, and then land, and after launching the game player is immediately killed. I'm using OnCollisionEnter, and I want to count to 2nd collision and then execute any action. How can I do this?
I'm not sure if this is the case anymore, but i had problem still in unity 4.6 when i had two colliders on same object, when other collided with something it called collision from both colliders, which in your case could result immediate increment x colliders. This happened with 2D Physics.
Answer by MrAkroMenToS · Apr 24, 2016 at 10:04 AM
Hi @kubawich
Declare a counter somewhere and increase it in the OnCollisionEnter block when you collide with the desired object. Upon collision add +1 to the counter, and when it reaches 2 then perform the action.
It should look something like this:
int counter = 0;
void OnCollisionEnter(Collision col) {
counter = counter + 1;
if (counter == 2) {
// Do your stuff
}
}
Or you can just spawn the player outside of the collider.
Acctually i tried this before, but problem is that OnCollisionEnter's working like loop, and when i spawn my player on floor the counter is incrementing through infinity, and destroy plyer object as fast as i start the game. Here's code for this http://pastebin.com/1NPc4XAg I used IsCollIncremented to not kill player immiedetly but idk how can I increment this just by one, not infinity :v
OnCollisionEnter sould work only once, upon entering the other collider, a dirty fix would be to say something like this:
void OnCollisionEnter(Collision col) {
if(Time.time > 1f){ // You can change '1f' to whatever you want, it is in seconds. It will be true when the game is running for at least 1 second, so basically you give the player a 1 sec long immunityFrame
// Do your stuff
}
Your answer
Follow this Question
Related Questions
Mesh deformation of a high poly 3D model causes FPS dropping 0 Answers
How can i look for collisions of the bulidngs in may array ? how can i use OnTRiggerEnter/exit ? 0 Answers
Attaching a script at runtime 2 Answers
How can I remove an object when colliding with an other object? 1 Answer
Issues on spawning the enemy? 0 Answers