- Home /
Spawn after every 5 seconds
Hey Guys, Johnny here :D I was just wondering if anyone knew how to spawn a gameobject after every 5 seconds. I'm creating a survival game where an enemy is spawned every 5 seconds. Is anyone able to help me out? Thanks so much :D
Answer by pcorazao · Mar 31, 2015 at 10:30 PM
public class BallHopperController : MonoBehaviour {
public GameObject ball;
public float spawnTime = 3f;
// Use this for initialization
void Start () {
InvokeRepeating ("SpawnBall", spawnTime, spawnTime);
}
// Update is called once per frame
void Update () {
}
void SpawnBall()
{
var newBall = GameObject.Instantiate(ball);
}
}
Answer by Dave-Carlile · Feb 13, 2013 at 05:35 PM
You can use Invoke to execute a function every 5 seconds. In that function Instantiate your game object.
Specifically, you might wanna use the repeating version: InvokeRepeating.
Answer by Razbijacs · Aug 21, 2019 at 05:56 PM
Time.time is counting time from the beginning of Play, i is checkpoint for Time.time to reach. As the Time.time reaches checkpoint,code is executed and the checkpoint is now moved for extra "i" seconds.I hope this helps all of you searching for the answer.
int i; // i=0.
public GameObject Enemy;
void Update()
{
if (Time.time> i)
{
i += 2;
Instantiate(Enemy,gameObject.transform);
}
}
, Time.time counts the real time seconds, and can only be red. "i" sets the check point for Time.time to reach,and when it reaches it code is executed and checkpoint is moved for additional "i" seconds.I hope this helps you all that are searching for a solution.
int i;
public GameObject Enemy;
// i==0;
void Update()
{
if (Time.time> i)
{
i += 5;
Instantiate(Enemy,gameObject.Transform.position);
}
}
float waitFor = 5f; waitFor -= time.time; if(waitFor >= 0) { //TODO waitFor = 5f; } // what is happening here?? i am sorry it might be stupid Q but i expect same result of your code from here, didn't work
Answer by SkillcraftHD · Feb 25, 2021 at 04:18 PM
Use an IEnumerator function with yield return new WaitForSeconds(5f) in it. Call it when you want it to first be spawned and also at the end of the IEunermator function.
Your answer
Follow this Question
Related Questions
Instantiating object after some fixed time... 2 Answers
How to change the colour of a light every few seconds. 1 Answer
Creating function that lasts for x seconds 3 Answers
Loading A Level After 40 Seconds 2 Answers
Randomize Spawn Time 2 Answers