Hello all, I am still new to unity and C#, and I have a question about Coroutines.
I have a simple AI targeting script that allows one gameobject to target the transform of another gameobject and move towards it. This script works well for my purposes, but it currently runs automatically when I hit the play button to test the game in Unity. I would like the script to start running only after the player presses a button.
What I attempted to do was to add a coroutine so that I could trigger the AI behavior(script) with a button press. However, when I added the coroutine to my script, the AI behavior runs for one frame when I press the button and then stops. I would like the function to continue running after I have pressed the button, as it did without the coroutine added in. Is there a way that this code can be changed to achieve this result? Here is the code for my AI script:
using UnityEngine;
using System.Collections;
public class EnemyAI: MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
private Transform myTransform;
void Awake()
{
myTransform = transform;
}
// Use this for initialization
void Start () {
GameObject go = GameObject.FindGameObjectWithTag ("Player");
target = go.transform;
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0))
StartCoroutine("AIScript");
}
IEnumerator AIScript()
{
myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
yield return null;
}
}
One of the ways that I attempted to solve my aforementioned problem, was to disable the “EnemyAI” script in the awake function, and then to enable it on a button press with this code:
EnemyAI otherScript = GetComponent<EnemeyAI>();
otherScript.enabled = false;
However, the “EnemyAI” script would not work while using this technique. I know that I can probably get this technique to achieve my desired result, because I used this same code to enable the “EnemyAI” script in the awake function, and then disable the script on a button press.
I am completely open to suggestions, so any help that you could offer would be greatly appreciated.
Thank you very much in advance.