- Home /
instantiate problem
when i instantiate between my prefabs they spawn at random places, not where i want them to, i need them to spawn in the y axis right where the prefab ended. heres my script 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.GetLength (0))], transform.position, Quaternion.identity);
Invoke ("spawn", Random.Range (spawnMin, spawnMax));
}
}
you're using transform.position, which will be the location of the object this script is attached to. Is that what you want?
Answer by _joe_ · Mar 29, 2015 at 03:57 PM
Using Instantiate(object, position, rotation), you will be adding the object to the position specified, in your case, it is "transform.position" which is the position of the object where you script (SpawnPlatforms) is added.
If you want to iteratively position your newly spawned prefabs one after the other on Y, you can do one of many things:
Save a counter, and position the new prefab based on that counter (for instance):
int spawnCount = 0;
float Offset = 5.0f;//pick the offset that is relative to your prefab size
void spawn(){
Vector3 newPosition = new Vector3(this.transform.position.x,
this.transform.position.y + spawnCount * Offest, this.transform.z);
Instantiate (obj [Random.Range (0, obj.GetLength (0))], newPosition, Quaternion.identity);
Invoke ("spawn", Random.Range (spawnMin, spawnMax));
}