- Home /
2D array loses all GameObjects on scene change despite objects don't destroy on load
Hi, I have a static 2D array to store the grid position of my "unit" GameObjects on a square-based battlefield of predefined size.
public abstract class PersistentPlayerSelections
{
// Unit position 2D arrays for both players, containing the unit prefabs at position x and y
public static GameObject[,] unitPositionArrayPlayer1;
public static GameObject[,] unitPositionArrayPlayer2;
// Initialize grid and character arrays during grid creation in Create2DGrid.cs
public static void InitializeArrays(int gridXNrRows, int gridYNrLines)
{
unitPositionArrayPlayer1 = new GameObject[gridXNrRows, gridYNrLines];
unitPositionArrayPlayer2 = new GameObject[gridXNrRows, gridYNrLines];
}
}
When I instantiate my "unit" GameObjects , I directly add them to this array. The units are set to "don't destroy on load". The array works perfectly fine in the initial scene, and shows the correct units in the correct 2D array field.
public void InstantiateCharacter(CharacterClass selectedCharacter, GameObject parentGameObject, GameObject[,] currentPlayerUnitArray)
{
// Create instance of the character prefab
newCharacter = Instantiate(selectedCharacter.characterPrefab, new Vector3 (0, 0, 0), transform.rotation * Quaternion.Euler(0, 0, 0));
newCharacter.transform.position = parentGameObject.transform.position; // place on correct grid position
// Add unit to unitPositionArrayPlayer1
posX = parentGameObject.GetComponent<GridTileStatus>().gridPosX;
posY = parentGameObject.GetComponent<GridTileStatus>().gridPosY;
currentPlayerUnitArray[posX, posY] = newCharacter; // Add to unit array
// Write stats from scriptable object characterClass to IndividualCharacter
charStats = newCharacter.AddComponent<IndividualCharacter>();
DontDestroyOnLoad(newCharacter); // Dont destroy the created characters during scene change
}
}
However, if I switch to the next scene, the array returns null in all fields, despite the original unit GameObjects staying on the scene unchanged (with all scripts attached etc.). They are also clearly sorted as "DontDestroyOnLoad" in the scene hierarchy.
So, if my static array stores these units, and these units are not destroyed, I would assume that my static array keeps the references on scene change? What am I missing here?
Thanks for your help!
PS: The "parentGameObject" is not really a parent, I just called it that in the constructor. So this shouldn't be the issue either.