unity add force away from object code example

Example 1: unity push in opposite direction of collision

void OnCollisionEnter(Collision c)
 {
     // force is how forcefully we will push the player away from the enemy.
     float force = 3;
 
     // If the object we hit is the enemy
     if (c.gameObject.tag == "enemy")
     {
         // Calculate Angle Between the collision point and the player
         Vector3 dir = c.contacts[0].point - transform.position;
         // We then get the opposite (-Vector3) and normalize it
         dir = -dir.normalized;
         // And finally we add force in the direction of dir and multiply it by force. 
         // This will push back the player
         GetComponent<Rigidbody>().AddForce(dir*force);
     }
 }

Example 2: how to add a force to an object unity

private Rigidbody2D rb;
public Vector2 direction;
public float force;

void Start()
{
	rb = GetComponent<Rigidbody2D>();
    rb.AddForce(direction * force, ForceMode2D.Impulse);
    //rb.AddForce(--pass in Vector--, --can pass in ForceMode--);
}