Spawner design for variable spawned units
Hi,
So I already have a spawner class working fine that spawns a unit based on an instantiation of a single predefined prefab. Great.
Now what I'd like is a spawner that is able to spawn from a selection of unit options, similar to what you see in Pixel Academy or Storm of Vengeance. I'd assume the user would have to define a roster to take with them into the level. Likewise, the enemy spawner would have preselected units as options.
For this to work, what is the best way to reference at runtime the available prefabs? Do I need a class that initially stores a reference to all the default prefab unitd? It would pass the user selected options to the spawner class as and when required? Or is there a more standard way that my inexperience is missing, assuming different unit types are 50+?
If any has a link to anything that I could learn from, that'd be great as I'm not necessarily asking for a coded solution to be provided.
Thanks
Answer by BongWater · Aug 21, 2016 at 08:34 PM
I belive what you're looking for is what's called an "Array" or "Object Array". Heres an example from one of my scripts I use to spawn coins on my 2d side-scroller project;
// This is the Array game object. The [] creates an array
public GameObject[] coins;
private float coinSpawnTimer = 7.0f;
void start () {
}
// Update is called once per frame
void Update () {
player = GameObject.FindGameObjectWithTag ("Player");
coinSpawnTimer -= Time.deltaTime;
if(coinSpawnTimer < 0.01) {
SpawnCoins();
}
void SpawnCoins() {
Instantiate (coins [(Random.Range (0, coins.Length))], new Vector3 (player.transform.position.x + 30, Random.Range (0, 3), 0), Quaternion.identity);
coinSpawnTimer = Random.Range (2.0f, 4.0f);
// The coins[(Random,Range (0, coins.Length))] means pick a random object between 0 (first object in array) and the arrays length.
When you assign the script to an object you'll get a drop down menu for the array, in my case Coins, then you drag and drop the prefabs into the menu, the first object being assined to "0". Hope this helps
Hi, I wasn't aware you could do this, and I will give it a go. $$anonymous$$y concern was is this the best way to handle this problem and is it very scalable? What if you want to assign your prefabs at runtime rather than via the UI?
Hi there, honestly I wouldn't know if this is the "best way" as it's the only way I know of. There could be ways to assign the values on runtime but again I wouldnt know, I havn't been using unity that long (just over a year) but hopefully this way works well enough for you