- Home /
Other
Declaring an Array as a combination of multiple other arrays?
Okay, so I'm currently working on a project in which I need to be able to randomly spawn certain objects in to the world. Currently, I'm working on ships. Basically, I want to be able to 'unlock' new ships, from separate arrays over time. Here's an example of what I mean. It's a snippet of code from the main spawning script that I'm working on.
public GameObject[] currentShips;
public GameObject[] starterShips;
public GameObject[] advancedShips;
public GameObject[] endShips;
private int randomShip;
void FixedUpdate () {
if (time >= 60) {
currentShips = starterShips, advancedShips;
if (time >= 180){
currentShips = starterShips, advancedShips, endShips;
}
}
Now, at the end there, you'll see that I've tried to declare an array as multiple others with a comma. Of course, this didn't work. So, how can I achieve this? currentShips is used later on to actually spawn a ship, picked at random from the currentShips.
Thanks in advance.
Answer by Regalith · Jun 09, 2014 at 07:39 PM
So the issue is that the arrays you're currently using have a set maximum size that have been allocated for them, which I'm guessing you've set in the inspector. So what you need is a type of array that is dynamic in size. I'd suggest using a list for current ships while leaving the rest static arrays so you can drag in game objects in the inspector. Here's some sample list code
using UnityEngine;
using System.Collections;
using System.Collections.Generics;
private List<GameObject> currentShips;
public GameObject[] starterShips;
public GameObject[] advancedShips;
public GameObject[] endShips;
private int randomShip;
void Start()
{
//Lists have to be initialized before using them
currentShips = new List<GameObject>();
//Add the start ships to the List
currentShips.AddRange(starterShips);
}
void FixedUpdate ()
{
if (time == 60)
{
currentShips.AddRange(advancedShips);
if (time == 180)
{
currentShips.AddRange(endShips);
}
}
}
Thank you very much, that's the exact kind of thing that I was looking for. I have a pretty patchy knowledge of Unity at the moment, so hopefully this can help me out in the long run, too. :P