Here is the code snippet:
NavMeshAgent agent;
public float targetStopTime;
public AudioClip strikeSound;
void Start ()
{
agent = GetComponent<NavMeshAgent>();
}
void OnTriggerEnter (Collider col)
{
if (col.gameObject.name == "ball(Clone)"){
AudioSource.PlayClipAtPoint(strikeSound, transform.position);
StartCoroutine("pauseTarget");
}
}
IEnumerator pauseTarget()
{
agent.Stop (true);
print("Waitting "+targetStopTime);
yield return new WaitForSeconds(targetStopTime);
print("Waited "+targetStopTime);
agent.Resume();
}
The yield statement works on the second print statement (it does wait before printing). But the agent.Stop(true) lasts only one frame and resumes. (tested with a value of targetStopTime = 5)
Ok, so, I have been on a geothermal job site for the past ten days and didn’t have time to work on this. But, today RAIN is stopping us from working so here I am and I came to what I think is an acceptable solution:
I combined both scripts into the following one and it seems to work well enough.
NavMeshAgent agent;
bool targetIsNotHit = true;
public Transform target;
public float targetStopTime = 5.0f;
public AudioClip strikeSound;
void Start ()
{
agent = GetComponent<NavMeshAgent>();
}
void Update ()
{
if (targetIsNotHit == true) {
agent.SetDestination (target.position);
}
}
void OnTriggerEnter (Collider col)
{
if (col.gameObject.name == "ball(Clone)"){
AudioSource.PlayClipAtPoint(strikeSound, transform.position);
StartCoroutine("pauseTarget");
}
}
IEnumerator pauseTarget()
{
targetIsNotHit = false;
agent.Stop (true);
yield return new WaitForSeconds(targetStopTime);
targetIsNotHit = true;
agent.Resume();
}
There is only one small issue: if I hit the target multiple times within the 5 second, it doesn’t reset the five seconds after each hit (but it doesn’t accumulate them either which is a good thing). I just need to see how to reset the five seconds as soon as a hit occurs, even if the last 5 seconds hasn’t ended.