Another way to achieve this would be to abandon Update altogether and just use a coroutine.
using UnityEngine;
using System.Collections;
public class AI : MonoBehaviour {
public Transform target;
public float moveSpeed = 50f;
float playerHealth;
public float attackSpeed = 1;
// Use this for initialization
void Start () {
playerHealth = target.GetComponent().curHealth;
StartCoroutine(Behaviour());
}
// Update is not used...
void Update () {}
IEnumerator Behaviour () {
while (true){
while (Vector3.Distance (target.transform.position, gameObject.transform.position) 2){
yeild return StartCouroutine(Move());
}
// Checking the player health first to avoid unneeded distance checks
while (playerHealth > 0 && Vector3.Distance (target.transform.position, gameObject.transform.position) 0){
yeild return StartCoroutine(Hit());
}
yield return null;
}
}
IEnumerator Hit() {
playerHealth -= 5;
yield return new WaitForSeconds (attackSpeed);
}
IEnumerator Move () {
transform.LookAt(target);
gameObject.transform.position += gameObject.transform.forward * moveSpeed * Time.deltaTime;
yield return null;
}
}
Trending Articles
More Pages to Explore .....