count on collision

im trying to create a "sphere" when my "ball" collides with it gets teleported to a set position, this all works but i would also like it to only be able to teleport 3 times and on the third go to another scene named "GameOver" this script below teleports it but i can't seem to get it to register and count how many times it hits. any suggestions welcomed

  public var destination : Transform; 
    public var life : int = 3;
    public var hit : int;

    function OnCollisionEnter (myCollision : Collision) {
     if(myCollision.gameObject.name == "Sphere"){
            transform.position = destination.position;
        }
    }

    function OnCollisionExit (theCollision : Collision) {   
        if(theCollision.gameObject.name == "Sphere"){
        hit ++;
        }
    }

    function Respawn() : void {
        if (++hit > life){
            Application.LoadLevel("GameOver");

        }
    }

Not sure if this is right, but it appears to me that the problem is that you're incrementing hit on collision exit, instead of on collision enter. That bit of code is never being called because its never "exiting" the collision. Once the collision starts, you teleport the object to the destination position so you're never "finishing" the collision.

What I would do is add a Debug.Log("Collision Exit!") or something like that on the OnCollisionExit function to see if it is actually ever calling it. It may be, but I am not sure if teleporting an object into a new spot is actually calling the function.

Also, if this is all the code you're trying to use, then nothing will ever happen since the Respawn function is never called.

I'd also clean it up and put the "hit ++;" within "OnCollisionEnter" along with Respawn within that same function. That way, workflow would be :

Check Collision - YES

  • Add 1 to hit.

  • call Respawn function (if hit > life then, it changes scene, if not, it continues)

  • change the position to be that of the destination.

That way, on the 3rd hit, it will just send you to the game over screen without changing the position.

You could do it like this:


 public var destination : Transform;
 public var life : int = 3;</p>

function OnCollisionEnter (myCollision : Collision)
{
  if(myCollision.gameObject.name == "Sphere")
  {
      transform.position = destination.position;
      life--;

      if (life == 0)
        Respawn();
   }
}

function Respawn() : void
{
    Application.LoadLevel("GameOver");
}