[Solved] Yet Another "Object reference not set to an instance of an object" issue.

Unity says error is on line 18, which is the “cameraControl.SetCameraTarget(planets[0].transform);” part. I’ve tried so many different ways of calling this line. I’ve also tried making quite a few changes on line 14 in case that was the root cause. I’m simply stumped. I know its something easy, my brain is just cheese atm. Any help would be appreciated.

Basic idea is that I’m setting up a camera that will (in another script/class) LookAt and move to what ever target is selected. I will then write some code that will enable me to pick/select/click/whatever new targets for the camera to look at, but i need this line to work first so i can be sure my other code follows suit and works as well. The purpose of this particular line of code is to programmatically pick the 1st planet that is instantiated and use it as the default/starting camera target.

All the rest of the code works fine, as tested by placing a prefab directly in the scene and manually making a public target variable and dropping a planet on it. The errors only started after i began making planets via instantiating them at run time rather than having static prefab objects sitting in the scene.

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public Planet[] planets;
    public GameObject mainCameraRig;
    public GameObject[] pPrefab;

    private CameraControl cameraControl;

    // Use this for initialization
    void Start ()
    {
        cameraControl = GetComponent<CameraControl>();

        SpawnAllPlanets();

        cameraControl.SetCameraTarget(planets[0].transform);
    }
 
    void SpawnAllPlanets ()
    {
        for (int i = 0; i < planets.Length; i++)
        {
            planets[i].pInstance = Instantiate(pPrefab[i], planets[i].distFromSun, planets[i].axisRotation) as GameObject;
            planets[i].NightLightIntensity = 0f;
            planets[i].Setup();
        }
    }
}

this is the setup method from a different script, just in case the error is actually there somewhere…

public void Setup()
    {
        rb = pInstance.GetComponent<Rigidbody>();
        rb.angularVelocity = Vector3.up * (rotateSpeed / -20);
    }

Also, sorry for the line numbers being off, the forums bot tells me I’m not allowed to edit my post when i try to fix it. =p

Just put some null checks and logs into your code. You’ll quickly find the error.
Make sure the component can be found and that the is actually set in the array.