- Home /
InvokeRepeating firing too often
I'm trying to make a defend-the-castle style game where enemies spawn on a line. The enemies spawn fine, but the InvokeRepeating in my script fires way too often. Not sure if this is user error, but I can't find any solution. Here'smy code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class EnemySpawnScript : MonoBehaviour { public Rigidbody enemy; void Start () { } void Update () { InvokeRepeating("SpawnEnemy", 1f, 1f); } IEnumerator waitForOneSecond() { yield return new WaitForSeconds(1); } void SpawnEnemy() { Vector3 EnemySpawnLoc = new Vector3(Random.Range(-25f, 25f), 1, 25); Instantiate(enemy, EnemySpawnLoc, Quaternion.identity); waitForOneSecond(); } }
$$anonymous$$oreover, I would like the "Enemy" to spawn once a second.
Answer by Legend_Bacon · Sep 18, 2018 at 04:54 PM
Hello there,
You should probably start by reading up on Coroutines and Invokes before you try to use them. They can be a little tricky.
So here's what's wrong with this script:
• You call InvokeRepeating in Update(). That means that every frame you start a new loop spawning an enemy every second. InvokeRepeating already, well... repeats without needing any additional work.
Move your InvokeRepeating to Start() and you'll be fine.
• Coroutines can't be called like regular functions. To call your WaitForOneSecond Coroutine, you need to call it like this: StartCoroutine(WaitForOneSecond());
• Calling a couroutine starts a parallel process, which means calling it from a regular function won't actually wait until that coroutine is done. For example, if you have:
private void Start()
{
Debug.Log("A");
StartCoroutine(WaitForOneSecond());
Debug.Log("B");
}
private IEnumerator WaitForOneSecond()
{
yield return new WaitForSeconds(1.0f);
}
You will get "A" and "B" in the same frame, WITHOUT a one-second delay.
However, for what you're trying to do here this code would work:
private void Start()
{
StartCoroutine(SpawnEnemiesCoroutine());
}
private IEnumerator SpawnEnemiesCoroutine()
{
yield return new WaitForSeconds(1.0f); // Initial Delay
while(true)
{
SpawnEnemy();
yield return new WaitForSeconds(1.0f);
}
yield return null;
}
I hope that helps!
Cheers,
~LegendBacon
This code got working right off the bat, again thank you!
Your answer
![](https://koobas.hobune.stream/wayback/20220612174848im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Instantiate Primitive Code Stopping Unexpectedly 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
continuous shooting 1 Answer
Why is instantiated animator prefabs are not working properly? 2 Answers