- Home /
i want tospawn objects
i want to spawn n egg like from snake game, but i want to spawn like, every 5 seconds spawn one, and after 5 seconds destroy it, and if destroys the player loses one life, if he loses 3 he losts, how can i do the egg spawning?i tried with instantiate but it keeps spawning over and over, the code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class eggs : MonoBehaviour { public Vector3 center; public Vector3 size; public GameObject Eggprefab; private float timeElapsed;
[SerializeField] private float delayEggs = 5f; [SerializeField] private float startDelay = 0f; [SerializeField] private float timeForSpawnEggs = 1f;
void Start(){
}
void Update(){ timeElapsed += Time.deltaTime; if (timeElapsed >= 4.99999 || timeElapsed <= 5.00001){ SpawnEggs ();}
}
void SpawnEggs(){ Vector2 pos = center = new Vector2(Random.Range(-size.x / 2, size.x / 2), Random.Range(-size.y /2, size.y / 2));
Instantiate(Eggprefab, pos, Quaternion.identity);
}
void OnDrawGizmosSelected() {Gizmos.color = new Color(1,0,0,0.5f); Gizmos.DrawCube(center, size);} }
Answer by Major_Lag · Feb 22, 2020 at 06:06 AM
You want to spawn every 5 seconds but in your update you're checking if time is greater than 4.9 seconds OR less than 5 which is a tautology. if you want to spawn in a interval it would be best to create a float defaulted to the spawn interval and then in update decrement it by deltatime and check if it reaches or goes below 0. If it does spawn your egg and reset your float back to your interval and repeat.
would probably look like:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class eggs : MonoBehaviour
{
public Vector3 center;
public Vector3 size;
public GameObject Eggprefab;
public float spawnPeriod = 5;
float timeElapsed;
[SerializeField] float delayEggs = 5f;
[SerializeField] float startDelay = 0f;
[SerializeField] float timeForSpawnEggs = 1f;
void Start()
{
timeElapsed = spawnPeriod;
}
void Update()
{
timeElapsed -= Time.deltaTime;
if (timeElapsed <= 0)
{
SpawnEggs();
timeElapsed = spawnPeriod;
}
}
void SpawnEggs()
{
Vector2 pos = center = new Vector2(Random.Range(-size.x / 2, size.x / 2), Random.Range(-size.y / 2, size.y / 2));
Instantiate(Eggprefab, pos, Quaternion.identity);
}
void OnDrawGizmosSelected()
{
Gizmos.color = new Color(1, 0, 0, 0.5f); Gizmos.DrawCube(center, size);
}
}
Your answer
Follow this Question
Related Questions
How do I randomly create 2 objects, each with a different shape and color? 1 Answer
Spawning Objects 1 Answer
Make Objects spawn within different screen sizes 0 Answers
How Increase And Decrease And Reset Spawn Rate Over 0 Answers
How do i make a "summon" object - and let the player face in its direction? 0 Answers