4 spawn locations, 4 prefabs
Good evening all,
I'm trying to set up a script that spawns 4 random prefabs at 4 locations i have set up as spawn locations. When I play the game, the objects all instantiate but two errors occur... 1) spawns 4 objects of the same color (but the color can change every time I rerun the game but still 4 of the same color) 2) they all spawn in the same location.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BucketSpawn : MonoBehaviour {
[SerializeField]
private GameObject[] spawnLocations;
[SerializeField]
private GameObject[] bucketPrefabs;
private int bucketsOnScreen = 0;
// Use this for initialization
void Start () {
int rndSpawnLocation = Random.Range(0, 3);
int rndBucketSpawn = Random.Range(0, 3);
while(bucketsOnScreen < 4) {
Instantiate(bucketPrefabs[rndBucketSpawn], spawnLocations[rndSpawnLocation].transform);
bucketsOnScreen++;
}
}
// Update is called once per frame
void Update () {
}
}
i've literally spent hours trying to figure out whats going on, and why it wont actually fetch a position for each individual piece rather than obtaining a random position for everything and setting it for all 4 pieces. i've tweaked it so much that now I cant even get them to spawn on the screen anymore. any help would be greatly appreciated.
Answer by TheCallipo · Jan 18, 2017 at 09:46 AM
The Start() Function only executes one time at the start of the scripts lifetime. Thats why the Random.Range Function only provides one number to your rndVariables.
Put the code in the Update() Function. The Update() Function is called every frame in the scripts lifetime.
Also make sure you access the "spawnLocations"-GameObjects position with spawnLocations[rndSpawnLocation].transform.position
Thank you for the reply! I've went ahead and moved my script to the Update function. It would appear it is still not working. It will spawn 4 buckets in the same location and the same color. Any ideas? @TheCallipo
Also, I used this to Instantiate the objects, they are now showing up.
Instantiate(bucketPrefabs[rndBucketSpawn], spawnLocations[rndSpawnLocation].position, spawnLocations[rndSpawnLocation].rotation);