How do i create a Magnet?

Im a total newb, but I want to know how to make a magnet, so that it will pick up objects close to it, like a scrap metal magnet.

I need to know how/what scripting needs to be done in javascript, or if someone can provide me with one. I have the model for the magnet, and various cubes which need picking up. Then, with the help of the magnet, I want to be able to move it around the environment, in order to drop the box into a container.

I was thinking of using some form of parenting, or perhaps applying gravity to the magnet, or some other technique. Also, how to transform the Magnet to make it go up and down using different keys to WASD, as thats already being used, preferably by using the space bar (hold space to make it go up, let go of space to make it go down).Any help will be greatly appreciated.


Broadly, I would:

  • Use OverlapSphere to return an array of all the colliders inside a radius around the magnet,
  • Iterate through the array, and use Rigidbody.MovePosition to move the objects towards the magnet,
  • Determine the positions by Lerping from the current position and desired position (so the further from the magnet, the less it moves towards the magnet)

You could also parent the objects to the magnet when they collide, and ignore any children of the magnet when you do your pass through the array to lerp their positions.

Comment back if you have trouble with these concepts, and I can attempt to explain in further detail!

After posting this, I found a similar question for magnet code, which approaches this problem in a very similar way, but has provided code as well.