Unity3D : Enemies following the player keep moving through each other

Hi,
I’m trying to make enemies follow the player, but also for them to collide with each other and other objects in my game. The “following” part works (I found some help for that here already), but as soon as I have multiple enemies, doesn’t matter where they’re placed, after some time chasing me they kind of all form into one, they overlap each other.
This is the code for following the player :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class follow : MonoBehaviour
{

	public Transform Player;

	public float MoveSpeed = 6f;
	float MaxDist = 30f;
	float MinDist = 5f;

	void Update()
	{
		transform.LookAt(Player);

		if (Vector3.Distance(transform.position, Player.position) >= MinDist)
		{

			transform.position += transform.forward * MoveSpeed * Time.deltaTime;

		}
	}
}

I’d really appreciate some help, I’ve been at this for quite some time.

If you want enemies to be affected by Physics, you have to work with Unity’s Rigidbody Component instead of modifying their position directly. If you set the position directly, the Rigidbody doesn’t know your “intention”, you might just want the object to “teleport” to its new position, rather than moving it smoothly and with respect to physics. To use Rigidbodies and allow collisions, try the following:

  • Attach a Collider component (e.g. “Sphere Collider”) to your player and to the enemies if you haven’t done so yet.
  • Attach a Rigidbody component to the enemies
  • Change
    transform.position += transform.forward * MoveSpeed * Time.deltaTime;
    to
    GetComponent&ltRigidbody&gt().velocity = transform.forward * MoveSpeed;