0

The function below is supposed to create a new instance of SolarSystem_Manager and add it to a list however when var clone = Instantiate(_solar) is run, it returns a nullreference error. All instances of _solar have the same ID when I created multiple and this was 0 and changing the variables of one also changes the variables of the others. Do you know what I am doing wrong?

private void createSolarSystem()
         {
             SolarSystem_Manager _solar = new SolarSystem_Manager();
             _solar.solarSystem = new SolarSystem(transform.GetComponent<Galaxy>(), Random.Range(9, 10), new List<LQPlanetManager>(), new SunManager());
             var clone = Instantiate(_solar);
             solarSystems.Add(clone);
         }
CR9GAMING
  • 13
  • 3
  • 1
    Please provide more details about your other classes. Is solar system manager a UnityEngine.Object? Instantiate only works with UnityEngine.Object types. As far as changing a variable changes across all "copies", those copies must be using the same ref instance to store data. – hijinxbassist Mar 30 '21 at 00:07
  • If however `SolarSystem_Manager` is a `UnityEngine.Object` (I guess a `MonoBehaviour`) type you **may NOT** use `new` to create it! You should get a warning about it – derHugo Mar 30 '21 at 07:20

1 Answers1

0

You shouldn't instantiate a Unity object with the new keyword. You should rather make a prefab of SolarSystem_Manager inside the editor and store it inside some variable:

  1. Add this to your class:

    [SerializeField] private GameObject _solarSystemManagerPrefab;

  2. Inside the editor, create a prefab and drag and drop it into _solarSystemManagerPrefab.

  3. Now you can instantiate your prefab like this:

    GameObject clone = Instantiate(_solarSystemManagerPrefab)

NandoErni
  • 111
  • 2