Making a game object follow the player C#

So first of all let me apologize if this is a stupidly simple question, I have only touched unity today. So I am trying to make a 2D game and I am having problems making an enemy sprite follow the player sprite. I have already made a script, that to me makes perfect sense, But doesn’t work:

using UnityEngine;
using System.Collections;

public class EnemyMovement : MonoBehaviour {


	[SerializeField]
	private GameObject player;
	private Rigidbody2D body;
	public Vector2 velocity = Vector2.zero;

	// Use this for initialization
	void Start () {
		body = GetComponent <Rigidbody2D> ();
	}
	
	// Update is called once per frame
	void Update () {
		if (transform.position.x > body.transform.position.x){
			body.velocity = velocity * -1;
		} else if (transform.position.x < body.transform.position.x){
			body.velocity = velocity;
		} else {
			body.velocity = new Vector2 (0,0);
		}
	}
}

I have set the velocity and the player game object yet the enemy sprite just sits there. If anyone could help that would be amazing. I just don’t want to find the fix but also know why this didn’t work.

Thank you.

I can’t see where you actually use the player’s position? Perhaps you meant if (player.transform.position.x > body.transform.position.x) etc?

Also, when you deal with Ridigbody components you should make changes to it in FixedUpdate not the normal Update method (see Unity - Scripting API: MonoBehaviour.FixedUpdate())

Lastly, you shouldn’t change the velocity value directly (it doesn’t like it) see: Unity - Scripting API: Rigidbody.velocity

Don’t worry, they are common pitfalls!

Try something like this:

 void FixedUpdate () {
        Vector2 toTarget = player.transform.position - transform.position;
        float speed = 1.5f;
        
        transform.Translate(toTarget * speed * Time.deltaTime);
    }

Disclaimer: I’m usualy in 3D not 2D so if anything acts a little strange it might be because of that - just add a comment and mention my name I’ll do what I can. Hope that helps!