Array error.

Anyone can point out the mistake? I dont know what go wrong. Error message is null reference in the for loop.

Thanks.

[System.Serializable]
public class Data
{
    public static GameData gameData = new GameData();

}


public class GameData
{
    public UniverseData universeData = new UniverseData();   
   
}


public class UniverseData
{
    public planet[] planets = new planet[Data.planetMax];

    public class planet
    {
        public Vector3 rotateAroundPivot;  // = new Vector3(Random.Range(0, 10), Random.Range(0, 10), Random.Range(0, 10)); So it every planet can rotate on different plane
        public float AngleAroundSun;            // = Random.Range(0,360), to make starting location for planet.
        public float rotateAroundSpeed;  // Cannot be too fast, otherwise space ship cannot arrive planet
        public Speciality speciality;      // = (Speciality)Random.Range(0, 23);
        public int[] specialitySupply = new int[Data.specialityMax];
    }  

       
}
public void NewGame()
    {      
        // Create Planets detail

        for (int i = 0; i < Data.planetMax; i++)
        {

            Data.gameData.universeData.planets[i].rotateAroundPivot = new Vector3(Random.Range(0, 10), Random.Range(0, 10), Random.Range(0, 10));
            Data.gameData.universeData.planets[i].AngleAroundSun = Random.Range(0, 360);
            Data.gameData.universeData.planets[i].rotateAroundSpeed = Random.Range(1, 2)*0.3f; // If too fast, space ship cant arrive planet           

            // clockwise or counter clockwise
            if (Random.Range(0, 1) == 0)
                Data.gameData.universeData.planets[i].rotateAroundSpeed = -Data.gameData.universeData.planets[i].rotateAroundSpeed;

            Data.gameData.universeData.planets[i].speciality = (Speciality)Random.Range(0, 23);

            for (int k = 0; k < Data.specialityMax; k++)
                Data.gameData.universeData.planets[i].specialitySupply[k] = 0;
                   

        }


        SceneManager.LoadScene("Universe");

    }

Nowhere have you filled the

public planet[] planets = new planet[Data.planetMax];

array with the instances of a planet. Might be the case.

public void NewGame()
{  
        // Create Planets detail
        for (int i = 0; i < Data.planetMax; i++)
        {
            Data.gameData.universeData.planets[i] = new UniverseData.planet ();
            // ...
        }
}

Thanks a lot. It work.

I am very confused with the array declaration,

I dont understand why
public planet[] planets = new planet[Data.planetMax];do not give all the instance. Don’t it declare all memory need?

All it does is create an array of references to the planet objects. Pretty much like declaring a single planet:

public planet myCoolPlanet;

This is a reference to the planet object, which hasn’t been assigned yet. Using myCoolPlanet in the current state also would result in the NullReferenceException.