2D platformer game enemy AI (simple patrol) problem. How to solve it (C#) ?

I wanted to make enemies whom can patrol with a given distance.

Everything is good until it reaches distance<=0.
I don’t know what is wrong with it.

problem

This is my code:

public class EnemyController : MonoBehaviour {

	public float speed = 3f;

	private float startingPositionX;
	public float endingPositionX = 5f;
	private float distance;
	private float originalDistance;
	private float originalPositionX;



	void Start(){
		startingPositionX = transform.position.x;
		distance = endingPositionX - startingPositionX;
		originalDistance = endingPositionX - startingPositionX;
		originalPositionX = transform.position.x;
	}


	void FixedUpdate(){
		if (distance >= 0) {
			rigidbody2D.velocity = new Vector2 (speed, rigidbody2D.velocity.y);
			distance = endingPositionX - transform.position.x;
			print (distance);
		}
		else if (distance <= 0) {
			startingPositionX = originalPositionX + endingPositionX;
			endingPositionX =originalPositionX;
			Flip ();
			print ("elerte");
			rigidbody2D.velocity = new Vector2 (-speed, rigidbody2D.velocity.y);
			distance = Mathf.Abs(endingPositionX - transform.position.x);
		}
	}

	void Flip(){
		Vector3 theScale = transform.localScale;
		theScale.x *= -1;
		transform.localScale = theScale;
	}

}

It’s in your if check. You have it to test “if the distance is more or equal to 0” and then “if it’s less or equal to 0”. So, there is a point where both statements are true, because when it goes to 0, both checks pass. Remove the = in one of the two checks.

Add Debug.Log to variables for find what cause problem. I think that problem or with distance calculation, so add Debug.Log(distance); or delete “=” from “else if”.

Weird, my answer is gone after it was converted from a comment.
Anyway… your issue is in the if statements. You have both of them to check for being equal to 0 as well as being less or more. So there is a moment that both checks are true, when your distance goes to 0. Remove the “=” from one of the two.
Probably on the first if.

SOLVED with this asset from the assetstore: Unity Asset Store - The Best Assets for Game Making