I have the code:
void OnTriggerStay(Collider co){
if (co.GetComponent<Monster> ()) {
GameObject g = (GameObject)Instantiate (bulletPrefab, transform.position, Quaternion.identity);
g.GetComponent<Bullet> ().target = co.transform;
}
}
this is so that when an enemy in my tower defense game enters the collider on the tower, the tower starts shooting the enemy. But with the current code it destroys the enemy instantly because there is no delay on the instantiate. Any help with this problem is much appreciated and keep in mind that I am a beginner. Thanks in advance!
There’s a bunch of ways you could do this. Personally I’m a big fan of Coroutines.
void OnTriggerStay(Collider co)
{
if (co.GetComponent<Monster> ())
{
StartCoroutine(InstantiateAfterDelay(1.0f)); // wait for one second
}
}
IEnumerator InstantiateAfterDelay(float delay)
{
yield return new WaitForSeconds(delay);
GameObject g = (GameObject)Instantiate (bulletPrefab, transform.position, Quaternion.identity);
g.GetComponent<Bullet> ().target = co.transform;
}
maybe you can put the two instantiate lines in a new method and call with the Invoke method. Unity - Scripting API: MonoBehaviour.Invoke
For a Tower Defense game, you would probably want the tower running a coroutine for firing at targets. If there are no targets, OnTriggerEnter() could be used to add a new target to its list (in fact, a List<> of targets may be a good choice for this, if it chooses a target randomly per shot or shoots multiple targets per shot). Then, the coroutine itself would make it fire on each after every X seconds.