How to spawn objects on a list of Transforms ?
public List<Transform> CubesPlace;
public GameObject cube;
// Use this for initialization
void Start()
{
for (int i = 0; i < Random.Range(1,27); i++)
{
cube = instantiate(???);
}
}
// Update is called once per frame
void Update () {
}
}
this is supposed to be a script that will instantiate a Gameobject at random position from the List of Transforms. Can someone help with the instantiate part ?
Answer by Hellium · Apr 27, 2017 at 07:58 AM
Your question is not very clear. Do you want to instantiate one object (as your question suggests) ou multiple (as your for
loop suggests) ?
void Start()
{
Vector3 position = CubesPlace[ Random.Range(0, CubesPlace.Count ) ].position ;
cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.GetComponent<Transform>().position = position;
}
Supposing you have a prefab to instantiate :
// Drag & Drop the prefab in the inspector
public GameObject prefab ;
void Start()
{
Vector3 position = CubesPlace[ Random.Range(0, CubesPlace.Count ) ].position ;
cube = Instantiate( prefab, position, Quaternion.identity ) ;
}
i want to be able to instantiate a prefab , random times and at random position everytime (i have the positions in the List)
I made a mistake in my answer (bad copy-paste)
In order to get a element from a List, you have to use brackets, not parenthesis
Answer by Bharad · May 02, 2017 at 06:45 PM
Hi,
Before using the script below, you need to create 2 or more empty game objects that will act as spawn points in the scene. These can be used to pass as input to transform array. public Transform[] spawnPoints;
void Start ()
{
InvokeRepeating ("Spawn", spawnTime, spawnTime);
}
void Spawn ()
{
int spawnPointIndex = Random.Range (0, spawnPoints.Length);
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
More details can be found in this Unity tutorial.