Question by
Tyronn · Feb 08, 2017 at 08:28 PM ·
c#waitforseconds
C# Wait time not working
so here is my script but for some reason the wait time doesnt work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using System.Linq;
using System;
public class ZombieToPlayer : MonoBehaviour {
public GameObject goal;
public int damping = 1;
public int mineID;
void Start()
{
gameObject.name = "Zam " + Zam.zamid;
mineID = Zam.zamid;
FindClosestEnemy();
}
void Update()
{
if (goal == null)
{
FindClosestEnemy();
}
else
{
FindClosestEnemy();
NavMeshAgent agent = GetComponent<NavMeshAgent>();
LookAtGoal();
agent.destination = goal.transform.position;
}
StartCoroutine(TestCoroutine());
}
void FindClosestEnemy()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Player");
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
goal = go;
distance = curDistance;
Debug.Log("obj set to =" + goal);
}
}
}
void SetTarget(string target)
{
goal = GameObject.Find(target);
NavMeshAgent agent = GetComponent<NavMeshAgent>();
LookAtGoal();
agent.destination = goal.transform.position;
}
void LookAtGoal()
{
Quaternion rotation = Quaternion.LookRotation(goal.transform.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}
void OnTriggerEnter(Collider other)
{
goal = null;
SetTarget(other.name);
}
IEnumerator TestCoroutine()
{
Debug.Log("TestCoroutine()");
yield return new WaitForSeconds(3);
}
}
Comment
Best Answer
Answer by Chikari · Feb 08, 2017 at 08:49 PM
First of all, the Coroutine won't slow down your Update() function. It's a _Co_routine.
So I assume you want to wait for your Debug.Log(). The problem is that you are Logging, and THEN you are waiting. If you want to slow down the Debug.log(), write:
IEnumerator TestCoroutine()
{
yield return new WaitForSeconds(3);
Debug.Log("TestCoroutine()");
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612110641im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Automatic reloading issues 1 Answer
C# waitForSeconds Question 1 Answer
WaitForSeconds 1 Answer
WaitForSeconds in c# not working 0 Answers
Coroutine WaitForSeconds ignoring StopAllCoroutines... How can I do it? 0 Answers