Picked Up Object Goes Through Walls

I have a script to pick up a cube like in portal, but when I pick it up It can move through walls and the floor. How can I stop this?

if (Physics.Raycast(transform.position, transform.forward, out hit, 4) && hit.transform.tag == "pickup")
            {
                //nothing
                cube = hit.transform.gameObject;
                cube.transform.position = cubepos.transform.position;
                cube.transform.localRotation = transform.rotation;
                cube.transform.SetParent(cubepos);
                cube.GetComponent<Rigidbody>().isKinematic = true;
            }

“cube” is the cube, “cubepos” is an empty gameobject in front of my camera. Why does my cube go through walls?
My cube has a rigidbody and a box collider, because without the box collider it falls through the floor.

When you set a rigidbody to be Kinematic, it can no longer be pushed by other objects. This is mostly used for things like walls that you don’t want objects like the player to push.

The following line of code basically makes it so physics doesn’t affect this object, but this object can affect the physics of other objects.
“cube.GetComponent().isKinematic = true;”

So how would I fix the problem? By removing this line? Because if I remove it the cube just flies all over the place because it has gravity and its not being held up by my player.

You could have an extra camera to render only the object tag and maybe hands? I did this once with an fps type, and it helped keep guns from clipping

I could, but players would still be able to drop a cube through a wall. I want the cube to hit the wall so they can’t break puzzles.

I would still recommend against using a kinematic rigidbody here.

To disable gravity, use “cube.GetComponent().useGravity= false;”

(this is a suggestion, there are probably other ways to do this) To prevent other random collisions, in the Editor go to Edit->ProjectSettings->Physics to set which physics layers will collide with which other layers. You can make a layer for “cube” and “held cube”, and have the “held cube” layer collide with fewer objects so it only collides with the wall. When you pick up the cube, you can set “cube.layer = LayerMask.NameToLayer(“held cube”);”.