- Home /
Instantiate Prefab at random times but keep 3 from spawning
I'm having an issue with one of my scripts. What I'm trying to do is instantiate my enemy prefab at random times and I had success in that.
My only problem is that I want it to spawn at random but I don't want the spawn points to spawn 3 in a row like you can see above. Here is my spawning script:
using UnityEngine;
using System.Collections;
public class spawnEnemy : MonoBehaviour {
public float time = 1.0F;
float realTime;
public GameObject enemy;
Random rnd = new Random();
public bool instancedPrefab = false;
// Use this for initialization
void Start () {
realTime = time;
StartCoroutine(enemySpawn());
StartCoroutine(timeChanger());
}
// Update is called once per frame
void Update () {
//GameObject.Instantiate(enemy);
}
IEnumerator enemySpawn()
{
while(true)
{
yield return new WaitForSeconds(realTime);
enemy.transform.position = this.gameObject.transform.position;
Instantiate(enemy);
}
}
IEnumerator timeChanger()
{
while(true)
{
yield return new WaitForSeconds(2);
int randFirst = Random.Range(1, 3);
int randSeccond = Random.Range(4, 6);
int randNumber = Random.Range(randFirst, randSeccond);
realTime = randNumber;
}
}
}
I don't really understand you question, you don't want to have 3 stars next to each other?
Ya I have the script above attached to each orange object. From time to time the spawn object each will spawn one at the same time causing 3 in a row. I can't have that happen.
Ins$$anonymous$$d of having the spawners use the script, why not modify it so a single controller deter$$anonymous$$es a random spawn time, and then selects which spawn position to use?
Answer by kevinspawner · Dec 22, 2014 at 10:47 AM
If I understood you right you don't want the starts to appear as a 3 in a row, So probably you can use Mathf.Random Range to create a randomness in position, rotation or sizes as per your need.
Answer by krowal · Dec 22, 2014 at 10:55 AM
Create another object where you will store time of last spawn of any star. when you have it, check if next spawn isnt happening too soon, if so, block it and wait for next spawn.