Hey Guys,
Johnny here
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
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);
}
}
You can use Invoke to execute a function every 5 seconds. In that function Instantiate your game object.
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);
}
}
Thankyou I’ll try it
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.