Search code examples
c#arraysunity-game-enginecamera

SetActive for multiple cameras


I have a working script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Interactive_map : MonoBehaviour
{
    
    public Camera[] cameras;
    
    void Start()
    {
        cameras[0].GetComponent<Camera>().enabled = true;                
    }
    
    public void TriggerClicked(int cam)
    {        
        for (int i = 0; i < cameras.Length; i++)
        {
            cameras[i].GetComponent<Camera>().enabled = false;
        }

        cameras[cam].GetComponent<Camera>().enabled = true;          
    }
}

But I need to disable and enable cameras entirely through SetActive() method. How can I do that correctly? Changing GetComponent<Camera>().enabled = true; to SetActive(True) causes a mistake

Assets\Scripts\Interactive_map.cs(13,20): error CS1061: 'Camera' does not contain a definition for 'SetActive' and no accessible extension method 'SetActive' accepting a first argument of type 'Camera' could be found (are you missing a using directive or an assembly reference?)


Solution

  • As @derHugo hinted at in their comment, SetActive(bool) is a GameObject method, not a Component method (the Camera class is a child of Component, so it inherits all Component's properties, including enabled).

    Therefore, you have to modify the Camera's GameObject through the .gameObject property, rather than changing the Camera directly:

    cameras[i].GetComponent<Camera>().gameObject.SetActive(false);
    

    As a side note, because your cameras array is already of type Camera, you don't need to use GetComponent<Camera>() on it. The call does nothing but make the enable/disable sequence ever so slightly slower:

    cameras[i].enabled = false;
    // or
    cameras[i].gameObject.SetActive(false);