Search Unity

Question Mutual attraction of objects and merging

Discussion in 'Scripting' started by Gorki12, Feb 23, 2021.

  1. Gorki12

    Gorki12

    Joined:
    Jul 12, 2015
    Posts:
    73
    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:
    Code (CSharp):
    1.  
    2.     void Update()
    3.     {
    4.         if (objectsInAreaList.Count > 0)
    5.         {
    6.             foreach (GameObject object in objectsInAreaList)
    7.             {
    8.                 if(object != null) object.transform.position = Vector3.MoveTowards(object.transform.position, gameObject.transform.position, 2f * Time.deltaTime);
    9.             }
    10.         }
    11.     }
    Trigger:

    Code (CSharp):
    1.     void OnTriggerEnter(Collider other)
    2.     {
    3. objectsInAreaList.Add(other.gameObject);
    4.     }
    Collision:

    Code (CSharp):
    1.     void OnCollisionEnter(Collision other)
    2.     {
    3.  
    4.         Instantiate(objectPrefab, gameObject.transform.position, Quaternion.identity);
    5.  
    6.         Destroy(other.gameObject);
    7.         Destroy(gameObject);
    8.     }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    You could do something cheeky like this:
    Code (CSharp):
    1.     void OnCollisionEnter(Collision other)
    2.     {
    3.         // Only one object should process the collision.
    4.         // Resolve the conflict by comparing instance ids.
    5.         int myId = gameObject.GetInstanceID();
    6.         int otherId = other.gameObject.GetInstanceID();
    7.    
    8.         if (myId > otherId) {
    9.             Instantiate(objectPrefab, gameObject.transform.position, Quaternion.identity);
    10.  
    11.             Destroy(other.gameObject);
    12.             Destroy(gameObject);
    13.         }
    14.     }
     
    Last edited: Feb 23, 2021
    Gorki12, Joe-Censored and SparrowGS like this.