Question by
Skinchanger29 · Sep 21, 2020 at 10:09 PM ·
c#aicoroutinefor-loop
How to get a for loop to run once per coroutine?
I am trying to make an AI (my first one without tutorials) and I am having a bug that completely ruins the AI. I have an array that I want to cycle through but instead of it adding one then going to the next point it goes straight from 0 for a while to 1,2,3 really fast, confusing the AI. Here is the script:
// Start is called before the first frame update
void Start()
{
noise = transform.GetChild(0).gameObject;
noiseAnim = GetComponent<Animator>();
chosenNo = 0;
chosen = patrol[chosenNo];
}
// Update is called once per frame
void Update()
{
StartCoroutine(Move());
Debug.Log(chosenNo.ToString());
}
IEnumerator Move()
{
if (noise.GetComponent<Soundwave>().sense == true)
{
lastKnownPoint = noise.GetComponent<Soundwave>().point;
transform.position = Vector2.MoveTowards(transform.position, lastKnownPoint.position, speed * Time.deltaTime);
yield return null;
} else if (noise.GetComponent<Soundwave>().sense == false)
{
if (transform.position == chosen.position)
{
for (; chosenNo < patrol.Length; chosenNo++)
{
noiseAnim.SetTrigger("Screech");
yield return new WaitForSeconds(waitTime);
chosen = patrol[chosenNo];
}
if (chosenNo >= patrol.Length || chosen == null)
{
chosenNo = 0;
}
}
if (transform.position != chosen.position)
{
transform.position = Vector2.MoveTowards(transform.position, chosen.position, speed * Time.deltaTime);
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Player")
{
noise.GetComponent<Soundwave>().sense = true;
noise.GetComponent<Soundwave>().player = collision.gameObject;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
StartCoroutine(Move());
}
Any help would be great thanks :)
Comment
Your answer
Follow this Question
Related Questions
How to get a for loop to run once per coroutine? 1 Answer
Why isn't my coroutine working when I call it from another script. 0 Answers
Any Way to Improve These Scripts or Increase Game Performance? 0 Answers
Coroutine only works one way 1 Answer
Wait time after coroutine's wait seconds is complete 0 Answers