- Home /
How to instantiate a GameObject initially, then have a timer count down?
Hey everyone, so I have these empty game objects in my game that are enemy spawners. When the player gets within a certain distance from a spawner, a timer starts and when a certain amount of time has elapsed an enemy spawns. The problem is that I don't know how to have an enemy spawn initially when the player is within the range of the spawner. As of now, when a spawner is activated by the player, there's just a wait for an enemy to spawn. Any help would be appreciated!
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class EnemySpawner : MonoBehaviour {
 
     public GameObject enemyPrefab;                  // holds enemy to be spawned
     public float distBetween;
     public float timer = 5f;
 
     private float timeElapsed;
     private Transform player;                       // holds the player
 
     void Start()
     {
         player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();          // get player position
     }
 
     void Update()
     {
         if (Vector2.Distance(transform.position, player.position) <= distBetween)
         {
             timeElapsed += Time.deltaTime;
             if (timeElapsed >= timer)
             {
                 Instantiate(enemyPrefab, transform.position, Quaternion.identity);
                 timeElapsed = 0f;
             }
         }
     }
 }
 
Answer by IronBytes · Mar 27, 2019 at 08:27 PM
You can use InvokeRepeating to trigger methods every X seconds:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html
You can then stop it again with CancelInvoke:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.CancelInvoke.html
So I came up with this code instead:
 private bool isActive = false;
 private int range = 10;
 
 void Update()
 {
     CheckToActivateSpawner();
 }
 
 void CheckToActivateSpawner()
 {
     if (!isActive && Vector3.Distance(transform.position, player.position) <= range)
     {
         InvokeRepeating("SpawnEnemy", 0, 5);
         isActive = true;
     }
     else if(isActive && Vector3.Distance(transform.position, player.position) > range)
     {
         CancelInvoke("SpawnEnemy");
         isActive = false;
     }
 }
 
 void SpawnEnemy()
 {
     Instantiate(enemyPrefab, transform.position, Quaternion.identity);
 }
Thanks a ton! I didn't even know about InvokeRepeating, this is exactly what I was looking for.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                