I use this simple script I whipped up to get mobs to follow on the X axis (but you could easily add a couple of lines to include Y axis as well because it already calculates that distance I just don't use it because I'm building a side scroller) I just created these functions in a MobAIMovement script and then called TotDistance from the Update function.
void TotDistance (){
var testX = transform.position.x;
var testY = transform.position.y;
var pTestX = target.transform.position.x;
var pTestY = target.transform.position.y;
var xDistance = testX - pTestX;
var yDistance = testY - pTestY;
var totDistance = Mathf.Pow (xDistance, 2) + Mathf.Pow (yDistance, 2);
totDistance = Mathf.Sqrt (totDistance);
Debug.Log ("Total Distance: " + totDistance);
FacePlayer (xDistance, totDistance);
}
void FacePlayer(float xDistunce, float tutDistunce){
if (xDistunce < -0.5) {
transform.localScale = new Vector3(-1, 1, 1);
if (tutDistunce > mobRange){
transform.Translate(1 * Time.deltaTime, 0, 0, Space.World);
anim.SetBool ("isMoving",true);
}
else{
anim.SetBool ("isMoving",false);
}
}
if (xDistunce > 0.5) {
transform.localScale = new Vector3(1, 1, 1);
if(tutDistunce > mobRange){
transform.Translate(-1 * Time.deltaTime, 0, 0, Space.World);
anim.SetBool ("isMoving",true);
}
else{
anim.SetBool("isMoving",false);
}
}
}
Very simple. It basically follows it on X, but stops once it is within range.(easily changed or removed.) It also flips the sprite to face and move left or right. The "isMoving" bool is just there to trigger the moving animation state and can be removed as well.
If I were you, I would change the (1 * Time.deltatime to 1 * mSpeed * Time.deltatime) and then set an mSpeed variable for the mob. That way if it isn't catching you, then you can speed up the mob by changing that variable.
If you want death to come from contact use OnCollisionEnter2D(collision2D coll) to detect collisions with player and destroy. If you want attack, then modify the script a bit. In the section where it stops within range you can change it to attack when it's within a totDistance instead of stop completely (which is all mine does at this second.)
One more thing, I'm pretty sure transform.forward won't work they you want in the 2D engine. You'll need transform.up or transform.right etc.
I'm no professional and still new to this all myself. Maybe this will help out. (I know my programming is probably archaic and not very efficient. Just figuring it out as I go along.)