- Home /
instantiates in the same place
I'm building a platformer, and I'm instantiating prefabs upwards, the problem is, that the prefabs can be instantiated on 1 another, causing multiple prefabs at the same spot, how can i generate them one AFTER another? there's my script, and its attached to a Quad attached to Main Camera using UnityEngine; using System.Collections;
public class SpawnPlatfoms : MonoBehaviour {
public GameObject[] obj;
public float spawnMin = 1f;
public float spawnMax = 2f;
// Use this for initialization
void Start () {
spawn();
}
// Update is called once per frame
void spawn(){
Instantiate (obj [Random.Range (0, obj.Length )], transform.position, Quaternion.identity);
Invoke ("spawn", Random.Range (spawnMin, spawnMax));
}
}
Answer by lordlycastle · Mar 30, 2015 at 06:42 PM
Don’t call a function from itself, that’s ridiculous. Put it in update if you want it go every frame indefinitely, or use loops; that’s what they are for, looping. If you want them to instantiate at different positions then just change the second argument of Instantiate
.
Vector3 lastObjSpawnPos = new Vector3()
void spawn(){
int index = Random.Range(0, obj.Lenght -1);
//If objects are different sizes, they need a collider to get their size.
lastObjSpawnPos.y += obj[index].GetComponent<Collider>().bounds.extends.y;
//otherwise you can just use cached size
lastObjSpawnPos.y += 2
Instantiate (obj [index], transform.position + lastObjSpawnPos, Quaternion.identity);
}
ummmm... I have a collider on each object, but my prefabs are like $$anonymous$$i levels that randomly generate, so I don't have a collider on the whole prefab but only on pieces from it. can i get the collider that its y position is the highest and from that collider +2? and also, it gives me an error UnityEngine.Bounds doesnt contain the definition for 'extends', maybe you meant extents?
Answer by hbalint1 · Mar 30, 2015 at 06:48 PM
I don't understand your question perfectly. Do you want them to instantiate one after another and upwards? Then I think you should make Spawn as a Coroutine and wait after each spawn. Also you have to increase the y coordinate :
public class SpawnPlatforms : MonoBehaviour
{
public int platformCount = 10;
public GameObject[] obj;
public float spawnMin = 1f;
public float spawnMax = 2f;
public float waitBetweenSpawns = 1f;
// Use this for initialization
void Start()
{
StartCoroutine(Spawn());
}
IEnumerator Spawn()
{
for (int i = 0; i < platformCount; ++i)
{
Instantiate(obj[Random.Range(0, obj.Length)], new Vector3(0, i * 3, 0), Quaternion.identity);
Invoke("spawn", Random.Range(spawnMin, spawnMax));
yield return new WaitForSeconds(waitBetweenSpawns);
}
}
}