Swapping whole arrays (or their references)
Well this is a tricky one: i'm currently working on a procedural level generator that spawns different prefabs depending on the phase the player has reached. I wonder if there's a way of "swapping" arrays so the whole generation code always references the "currentArray" instead of having multiple copies of the same script with the variable name changed, because that's really inefficient. I wanted to archieve something like this:
if (beginFirstPhase && !firstPhaseBegun)
{
currPhaseArray = firstPhaseArray;
firstPhaseBegun;
beginFirstPhase = false;
}
if (beginSecondPhase && !secondPhaseBegun)
{
currPhaseArray = secondPhaseArray;
secondPhaseBegun;
beginSecondPhase = false;
}
Unfortunately arrays do not sync unless "currPhaseArray" has ben assigned the same length as the target array, which defeats the whole purpose of using arrays of varying lengths. As far as I know arrays cannot change their length during runtime, and even if such a thing was possible I don't know if it still works after compilation, but if it was it would solve my problem (I think)
Thanks in advance! I've been working on this script for days and it's driving me mad.
You could look through the phaseArrays, and find the longest one. All of the arrays can use that length. If they are the same length, you can easily swap them as you described above.
Let's say that the firstPhaseArray contains 3 elements, the secondPhaseArray contains 4 elements. Both of them could have the length of 4 despite of the first array containing only 3 elements.
When you want to instantiate the gameobjects in the array, you can simply avoid getting NullReferenceException errors with:
for(int i = 0; i < firstPhaseArray.Length; i++)
{
if(firstPhaseArray[i] != null) GameObject.Instantiate(firstPhaseArray[i]);
}
Your answer
Follow this Question
Related Questions
Why UNITY Hates Me By Reading Array's Length! 1 Answer
Change max range attribute? 0 Answers
I'm trying to shuffle an array's order 3 Answers