How Do I Freeze Position ?

I have two cubes and when they collide, I would like for them to remain in contact.

However, they eventually break contact on their own. So, I’ve tried to prevent them from separating by freezing their positions. But, alas, it doesn’t seem to be working. I’ve tried this in “OnCollisionEnter” and I’ve tried it in “OnCollisionStay” but it doesn’t seem to work in either place.

The code follows…might someone offer a suggestion to keep my cubes from separating on their own?

Thank you in advance.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Combat02 : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	void OnCollisionEnter(Collision col)
	{
		if (col.gameObject.tag == "Ally") 
		{
			
			col.gameObject.GetComponent<Renderer> ().material.color = Color.cyan;
			//col.rigidbody.constraints = RigidbodyConstraints.FreezePosition; 

		}
	}

	void OnCollisionStay(Collision col)
	{
		if (col.gameObject.tag == "Ally") 
		{
			col.rigidbody.constraints = RigidbodyConstraints.FreezePosition;
		}
	}
}

Hi Topthink

Enabling the “FreezePosition” of the Rigidbody basically prevents the GameObject from moving at all.
If you do this to both of them, they won’t move. If you do it to one… this one won’t move and the second one moves away from the first one.
That’s not your way to go.

To move both of them together you could make one of them a child of the other. Disabling the Collider should prevent them from colliding again.

void OnCollisionEnter(Collision col)
 {
         if (col.gameObject.tag == "Ally") 
         {
                 col.gameObject.GetComponent<Renderer> ().material.color = Color.cyan;
                 col.gameObject.transform.parent = transform;
                 col.enable = false;
         }
}

Hi, a simple way can be attaching a fixed joint on Collision enter.