We are creating a simple AI for a platform game, wherein a number of enemies are patrolling a certain platform. They will change direction if they reach the edge of that platform. Since they are all going to do the same kind of behavior, we just made a prefab of that enemy, with a script attached to it.
So we duplicated them and placed them in different places, and just changed the values of the left and right limits in the inspector.
However, they are all changing directions at the same time, even if one enemy hasn’t reached the limit yet.
Here’s the script:
using UnityEngine;
using System.Collections;
public class EnemyPatrol : MonoBehaviour {
public float RightSpeed = 2.0f;
public float Leftspeed =- 2.0f;
public Animator anim;
public string axisName = "Horizontal";
public float speed = 1.0f;
public float RightEdge;
public float LeftEdge;
public static bool isRight = true;
private Transform myTransform;
// Use this for initialization
void Start () {
anim = gameObject.GetComponent<Animator>();
myTransform = transform;
int rand = Random.Range(1, 2);
if(rand == 1) isRight = true;
else isRight = false;
}
// Update is called once per frame
void Update () {
anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis(axisName)));
if (isRight) {
Vector3 newScale = myTransform.localScale;
newScale.x = 1.0f;
myTransform.localScale = newScale;
myTransform.position += myTransform.right * RightSpeed *Time.deltaTime;
}
else if (!isRight) {
Vector3 newScale = myTransform.localScale;
newScale.x = -1.0f;
myTransform.localScale = newScale;
myTransform.position += myTransform.right * Leftspeed *Time.deltaTime;
}
if(myTransform.position.x > RightEdge){
isRight = false;
}
else if(myTransform.position.x < LeftEdge){
isRight = true;
}
myTransform.position += myTransform.right * Input.GetAxis(axisName) * speed * Time.deltaTime;
}
}
What seems to be the problem? Thanks for your help.