Slight pause when collision with pickup item

I'm using the code below in my Collisions.js file and my pickups work fine but there is about a half second pause in the characters forward movement. It's enough to be noticeable. What am I doing wrong? Thanks.

static var GEAR_COUNT = 0;
static var PLAYER_LIFE = 100;

function OnCollisionEnter (collision:Collision) 
{
    if(collision.gameObject.tag == "Gear")
    {
        // Add Gear To Inventory
        GEAR_COUNT += 1;
        print("You've Collected " + GEAR_COUNT + " Gears!");

        // Destroy The Gear
        Destroy(collision.gameObject);
    }
    else if(collision.gameObject.tag == "Battery")
    {
        // Add Battery Power To Player's Life
        PLAYER_LIFE += 25;
        print("You've Collected A Battery");

        // Destroy The Battery
        Destroy(collision.gameObject);
    }
}

1 Answer

1

In order for the collision to register, the collider would have to collide, which causes the pause you noticed. In order to avoid this, use the OnTriggerEnter function in conjunction with trigger colliders to achieve the same effect while avoiding the pause. Your script would look like this:

static var GEAR_COUNT = 0;
static var PLAYER_LIFE = 100;

function OnTriggerEnter(other : Collider) {
    if (other.gameObject.CompareTag("Gear")) {
        //Add gear to inventory
        print ("You've Collected " + GEAR_COUNT + " Gears!");

        //Destroy the gear
        Destroy(other.gameObject);
    }

    else if (other.gameObject.CompareTag("Battery")) {
        //Add battery power to player's life
        PLAYER_LIFE + 25;

        //Destroy the battery
        Destroy(other.gameObject);
    }
}

In order for this to work you'll need to set the colliders on your battery and gear objects to be triggers.

Please note that the above script is untested and may contain errors.

Perfect. Thanks so much.

No problem, glad I could help. :)