Unity2d Set Different Physics Properties on Gameobjects (potentially at Runtime)

I currently have two gameobjects of the same prefab interacting with physics but cannot get the right settings to make it do what I want.

What I have is:

When I make the red controllable gameobject move into the blue character it nudges the blue gameobject.

What I want is:

  • if blue object is selected, red gameobject acts as an impassable wall to the blue gameobject.
  • if red object is selected, blue gameobject acts as an impassable wall to the red gameobject.

Here is the snippet of code I am using to make the selected gameobject move with keyboard input

SelectedGameObject.rigidbody2D.velocity = new Vector2(xCom, yCom).normalized * 5;

Current settings for my two gameobjects are shown in the inspector

I could suggest you use rigidbody constraints. But as it is 2D you can not because unity didin’t implement it in 2d. So you can set the non selected objects rigidbody to kinematic by doing this:

Rigidbody2D.isKinematic = true

If that doesn’t work then always set the not selected object’s velocity to 0

Also don’t forget to set fixedAngle value to true on the not selected object by doing this:

Rigidbody2D.fixedAngle = true

I hope it helps. It would be the way easier with constraints but I don’t know why it’s not implemented in 2D rigidbody

Slight update, In Unity it looks like if you have a collider without a rigidbody for all intents and purposes that object is considered static so the way I have hacked this is by adding and removing the rigidbody attached to all of the gameobjects based on whether I have it selected/am in control of moving it. Going to leave this question up for a day or two to see if anyone knows a ‘better’ way to do this else I’ll just mark it as solved afterwards

void Update ()
	if (this.gameObject == GameManager.SelectedGameObject)
		if (this.gameObject.rigidbody2D == null)
		if (this.rigidbody2D != null)
			Destroy (this.rigidbody2D);