Mutual attraction of objects and merging

I want to get the effect that when the two objects collide, they are removed and an enlarged model is created.
But when collision detect they are deleted, two or more objects are created, and I want one to be created.

objectsInAreaList is list which stores objects that are in collision with the trigger on.

Move script:

    void Update()
    {
        if (objectsInAreaList.Count > 0)
        {
            foreach (GameObject object in objectsInAreaList)
            {
                if(object != null) object.transform.position = Vector3.MoveTowards(object.transform.position, gameObject.transform.position, 2f * Time.deltaTime);
            }
        }
    }

Trigger:

    void OnTriggerEnter(Collider other)
    {
objectsInAreaList.Add(other.gameObject);
    }

Collision:

    void OnCollisionEnter(Collision other)
    {

        Instantiate(objectPrefab, gameObject.transform.position, Quaternion.identity);

        Destroy(other.gameObject);
        Destroy(gameObject);
    }

You could do something cheeky like this:

    void OnCollisionEnter(Collision other)
    {
        // Only one object should process the collision.
        // Resolve the conflict by comparing instance ids.
        int myId = gameObject.GetInstanceID();
        int otherId = other.gameObject.GetInstanceID();
    
        if (myId > otherId) {
            Instantiate(objectPrefab, gameObject.transform.position, Quaternion.identity);

            Destroy(other.gameObject);
            Destroy(gameObject);
        }
    }
3 Likes