C# Script for Creating a Rigidbody Magnet in Unity

Below is the script that generates magnet-like behavior toward the Rigidbodies in Unity:

Sharp Coder Video Player

Steps

  • Create a new script, call it SC_RigidbodyMagnet then paste the code below inside it:

SC_RigidbodyMagnet.cs

using System.Collections.Generic;
using UnityEngine;

public class SC_RigidbodyMagnet : MonoBehaviour
{
    public float magnetForce = 100;

    List<Rigidbody> caughtRigidbodies = new List<Rigidbody>();

    void FixedUpdate()
    {
        for (int i = 0; i < caughtRigidbodies.Count; i++)
        {
            caughtRigidbodies[i].velocity = (transform.position - (caughtRigidbodies[i].transform.position + caughtRigidbodies[i].centerOfMass)) * magnetForce * Time.deltaTime;
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.GetComponent<Rigidbody>())
        {
            Rigidbody r = other.GetComponent<Rigidbody>();

            if(!caughtRigidbodies.Contains(r))
            {
                //Add Rigidbody
                caughtRigidbodies.Add(r);
            }
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.GetComponent<Rigidbody>())
        {
            Rigidbody r = other.GetComponent<Rigidbody>();

            if (caughtRigidbodies.Contains(r))
            {
                //Remove Rigidbody
                caughtRigidbodies.Remove(r);
            }
        }
    }
}

  • Create a new GameObject and assign the SC_RigidbodyMagnet script to it
  • Add a Sphere Collider to a newly created object, mark it as Trigger then increase its radius
  • Create a couple of Cubes and add a Rigidbody component to them

Press Play then move the Object with SC_RigidbodyMagnet script over the Rigidbodies, notice how the Rigidbodies are being pulled in.

Suggested Articles
Working with Unity's Rigidbody Component
Creating a Physics-Based Racing Game in Unity
Creating a Flag Simulation in Unity
Creating a Rocket Launcher in Unity
Make Tornado Physics in Unity
Implementing Mining Mechanics in Unity Game
How to Check if a Rigidbody Player is Grounded in Unity