How to spawn a prefab every 5 second randomly between a set range?
I'm struggling to spawn a prefab in without it being a gameobject, and I want it one to spawn in every 5 seconds between a set range? any help would be appreciated!
public class obstacle : MonoBehaviour {
private Rigidbody2D rb2d;
private float obstacleSpawnCounter;
public Vector3 spawnPosition;
public GameObject spike;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>();
rb2d.isKinematic = true;
GetComponent<SpriteRenderer>().sortingOrder = 4;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
if (rb2d.isKinematic)
rb2d.isKinematic = false;
}
obstacleSpawnCounter += Time.deltaTime;
if (obstacleSpawnCounter > 5)
{
SpawnObstacle();
obstacleSpawnCounter -= 5;
}
this.transform.Translate(0, 0.06f, 0);
}
public void SpawnObstacle()
{
Instantiate(spike, spawnPosition, Quaternion.identity);
}
}
Hi there, could you elaborate on your question a little more? I'm not entirely sure I understand what you're after.
Hi, I basically want to spawn a prefab onto the scene without it being attached to an empty gameobject and to spawn randomly between a set range every 5 seconds. At the moment it will only spawn when I make an empty gameobject and attach the prefab and script but it glitches every time it spawns and spawns like 20, any ideas??
Ok, you need to give it the spike prefab not an empty GameObject
I'm still not entirely sure what the random value is for but $$anonymous$$ath.Random()
exists so look into that.
When resetting a float responsible for handling deltaTime it's best to reset using 0 rather than removing the value you think it has, as doing it via the latter can create irregular behaviour.
Your answer
Follow this Question
Related Questions
how to Spawn prefab infront off player and destroy it when hr passed it 0 Answers
Instantiating prefab causes existing instances to change values 1 Answer
How do you spawn a gameobject based on last object in array and limit that within a range? 1 Answer
Random Object Spawn 0 Answers
Random spawn on screen 1 Answer