Quantcast
Channel: Answers for "How to end this infinite loop problem in C#!?"
Viewing all articles
Browse latest Browse all 6

Answer by BoredMormon

$
0
0
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; } }

Viewing all articles
Browse latest Browse all 6

Latest Images

Trending Articles





Latest Images