One Enemy Object Moves, But The Others Do Not

I have a scene with three enemies in it. They all share the same script. I just duplicated the first enemy gameObject. The original enemy gameObject works exactly as I want it to, but the other two don’t.

Here is my code:

using UnityEngine;
using System.Collections;

public class EnemyMovement : MonoBehaviour {
	//Variables
	public float speed = 2.0f;
	
	private float boundary1;
	private float boundary2;

	private bool goingLeft;

	public int left;
	public int right;

	// Use this for initialization
	void Start () {
		boundary1 = transform.position.x - left; //left boundary
		boundary2 = transform.position.y + right; //right boundary
		goingLeft = false;
	
	}
	
	// Update is called once per frame
	void Update () {
		if (transform.position.x < boundary2) { //less than right boundary going right
			if (goingLeft == false)
				transform.Translate (Vector3.right * Time.deltaTime * speed);
		}
		else
			goingLeft = true;

		if (transform.position.x > boundary1) { //greater than left boundary going left
			if (goingLeft)
				transform.Translate (Vector3.left * Time.deltaTime * speed);
		} 
		else
			goingLeft = false;
	}
}

Basically what my object does, is go continuously between one boundary and the other. Works for one gameObject, but the two other ones just go to one boundary and stops. I don’t really understand how that could happen. What is going wrong?

try making

private bool goingLeft;

into

static bool goingLeft;

:slight_smile:

Player is always going to be between left and right boundary, so both if statements are always going to be true. Kinda beats it’s purpose. So the else part will never the used. Below I check when player moves out of the boundary, when he does, I change the direction. Try this:

 if (transform.position.x > boundary2 || transform.position.x < boundary1) 
     goingLeft = !goingLeft;
var dir = goingLeft ? Vector3.left : Vector3.right;
transform.Translate (dir * Time.deltaTime * speed);

Maybe I found the answer. You should only use two positive numbers as the two boundaries. If you put negatives (or one negative, one poisitive) it will give strange result and it will stop. If i try with two positives then it’s erfect, but if i try like: right= -5; left = 3; I get the same result as you. So only use positive numbers!