Processing scripts only once for two equivalent colliders?

Hoping this is pretty straightforward

The following script is intended to have two objects collide and check for the correct collider type before destroying them both and replacing them with a new gameobject:

var newObject:GameObject;

function OnCollisionEnter (collision : Collision) 
{
    var contact = collision.contacts[0];
    if(contact.otherCollider.name == "rightObject")
        {
            Destroy(contact.otherCollider.gameObject);
            Destroy(contact.thisCollider.gameObject);
            var newVelocity:Vector3 = (transform.rigidbody.velocity + contact.otherCollider.attachedRigidbody.velocity)/2;
            var newPosition:Vector3 = contact.point; 
            var newObject2:GameObject = Instantiate(newObject, newPosition, Quaternion.identity);
            newObject2.transform.rigidbody.velocity = newVelocity;
        }
    
}

As one might expect, the code executes oce on each of the objects, resulting in two new objects instantiated instead of one… I was hoping that either:

  1. The object that moved that frame (causing the collision) could be considered the “collider” and the receiver the “collidee” and that I could execute the script for only the collider, or:
  2. I had hoped that by destroying both objects as early as possible, that only the first one processed would run the script (turns out to not work that way… both objects process it)

Is there a simple way to force the script to only be executed once when these kinds of symmetrical collisions occur?

Regards!

Tz.

One possibility is you could check their positions. Something like:

if (transform.position.x > contact.otherCollider.transform.position.x)
{
}

This will only execute one of them.

A more robust way is to set a flag in the other game object that the collision has already been processed:

Btw I assume this script is called MergeOnCollision. Replace both places I use that name with the real name of the script (without the file extension).

var newObject:GameObject; 

var alreadyCollided=false;

function OnCollisionEnter (collision : Collision) 
{ 
    if (alreadyCollided) return;
    var contact = collision.contacts[0]; 
    var otherMerger : MergeOnCollision = contact. otherCollider .GetComponent(MergeOnCollision);
    if(contact.otherCollider.name == "rightObject" ) 
        { 
            Destroy(contact.otherCollider.gameObject); 
            Destroy(contact.thisCollider.gameObject); 
           
            if(otherMerger)
                otherMerger.alreadyCollided=true;

            var newVelocity:Vector3 = (transform.rigidbody.velocity + contact.otherCollider.attachedRigidbody.velocity)/2; 
            var newPosition:Vector3 = contact.point; 
            var newObject2:GameObject = Instantiate(newObject, newPosition, Quaternion.identity); 
            newObject2.transform.rigidbody.velocity = newVelocity; 
        } 
    
}