-2

i'm making a game in Unity and I have made a script that allows me to switch cameras within my scene. here's the code for it.

public class ChangeCamera : MonoBehaviour
{
    public Camera[] cameras;  // Array to hold your cameras
    private int currentCameraIndex;  // Index of the current active camera

    MainTurret mainTurret;
    private void Start()
    {
        // Set the first camera as the starting camera
        currentCameraIndex = 0;
        ActivateCamera(currentCameraIndex);
        
        mainTurret = FindObjectOfType<MainTurret>();
    }

    private void Update()
    {
        // Check for key input to switch cameras
        if (Input.GetKeyDown(KeyCode.T))
        {
            SwitchCamera();
        }
    }

    public void SwitchCamera()
    {
        // Deactivate the current camera
        cameras[currentCameraIndex].gameObject.SetActive(false);

        // Increment the camera index
        currentCameraIndex++;

        // Wrap around to the first camera if the index goes beyond the array size
        if (currentCameraIndex >= cameras.Length)
            currentCameraIndex = 0;

        // Activate the new camera
        ActivateCamera(currentCameraIndex);
    }

    private void ActivateCamera(int index)
    {
        // Activate the specified camera
        cameras[index].gameObject.SetActive(true);
        if (cameras[index].gameObject.tag == "turret")
        {
            mainTurret.GetComponent<MainTurret>().SetActive();
            
            cameras[index].enabled= true;
            Camera.main.enabled = false;
        }
        else if (!(cameras[index].gameObject.tag == "turret"))
        {
            mainTurret.GetComponent<MainTurret>().SetNotActive();
            cameras[index].enabled= false;
            Camera.main.enabled = true;
        }
    }
}

although when i run my project. it gives me a null reference exception here,

mainTurret.GetComponent<MainTurret>().SetNotActive();

and here,

            mainTurret.GetComponent<MainTurret>().SetActive();

any reason why is that, i have the mainTurret instantiated above and i tried several methods but nothing seems to work.

1 Answers1

1

Your mainTurret is instantiated in the Start() method by the line mainTurret = FindObjectOfType<MainTurret>();

So if you call the ActivateCamera() method before the Start() method, it will throw the exception because your "mainTurret" variable is null.

TP95
  • 175
  • 8