How to prevent a moving platform from pushing other objects through the scenery?

In my test scene I have five objects, four of which are really relevant to this question: There are:

  • a top block with only a box collider
  • a bottom block with only a box collider
  • a cube just between these two with a box collider and a rigibody
  • a moving platform with a "Lift controller" script that makes it move up or down and a "Push bodies" script (taken from the 2D gameplay tutorial).

When I move the platform, initially, there is no problem. The cube lands on the platform and moves realistically. Now when I keep on pushing the platform up till it gets close to the upper block (a sort of boundary) it pushes the rigidbody cube through this top block. The behavior I would like is a 'stacked' kind of movement, which doesn't allow the platform to push through. Also, the platform itself, when the cube isn't even there, moves through the top block, even though I added the box collider. Is there a way for all these blocks (and in the future every added block) to not be able to move through each other but act as rigidbodies even though they're not?

my lift code on the moving platform:

function Update () {
 transform.position.y += Input.GetAxis("Vertical") * Time.deltaTime;

The moving platform will eventually be an elevator, so pushing stuff through other stuff is not a convenient situation :)

Setting the location of a transform directly is seen like a "teleport" by the physics engine: It doesn't know how the object got there; only that it is now suddenly there.

If you want physical objects to be stopped when they collide with other things, you need to drive the movement with forces, or set the velocity, rather than applying changes directly to the transform. Just add a Rigidbody to the GameObject, then you have access to the rigidbody variable in your scripts.

See the scripting reference on Rigidbody to get an idea of your options.

Your code could be like this (you don't need to use deltaTime when working with velocity - it's implicit):

function Update () {
    rigidbody.velocity.y = Input.GetAxis("Vertical");

you should make the top and bottom blocks kinematic rigidbodies. in this way the cube will collide with them and stops moving. in order to stop the platform you should implement the OnTriggerEnter function for the platform and see if the other collider is a block stop moving. or just do a raycast in each update when you get input and then move the platform if there is enough empty space to move.