- Home /
My C# Script Won't Switch Camera
Hey, I'm extremely new to unity, c#, and just coding in general. I'm making a little game and want to make my camera switch when my player object is destroyed (my main camera is attached to my player and is also destroyed, so that's why). Since I'm new, I try to code by myself and follow tutorials instead of just copy code. I understand that means I'll make a lot of errors. Here is one I just can't find my way around.
public class NewBehaviourScript : MonoBehaviour { // Update is called once per frame void Update() { MakeMain(GameObject.Find("Camera1")); } void MakeMain(GameObject secondary) { if(Camera.main == null) { secondary.gameObject.SetActive(true); } } }
When my player object is destroyed the Camera.main will come back null. I have my Camera1 cam set unactive. I'm not sure why it isn't being set to active after my main camera is destroyed and being displayed on the screen. It just says, "Display 1 No cameras rendering". I have the script set to Camera1 currently, which I think that's how it should be. This might be a little confusing (I'm confused), but a little help would be awesomely appreciated. Again, you might think I'm dumb, but I'm just really new to this. If you need any more clarification on my question, I'll reply ASAP. Thanks so much!
Answer by DemocracyDealer · Jul 16, 2020 at 11:56 PM
That was not the fix. In fact, it is far more simple. I ended up changing the camera true/false instead. Here is the final script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class thing : MonoBehaviour
{
private Camera myCamera;
// Start is called before the first frame update
void Start()
{
myCamera = GetComponent<Camera>();
myCamera.enabled = false;
}
void Update()
{
MakeMain();
}
void MakeMain()
{
myCamera = GetComponent<Camera>();
if (Camera.main == null)
{
myCamera.enabled = true;
}
}
}
Answer by jemules · Jul 16, 2020 at 07:51 PM
Here the fix https://pastebin.com/xx0w83jH
I'm not sure why, but that didn't work. I added the cameras in the inspector, and yet it still says, "Display 1 No cameras rendering". This is a big hassle, and I'm not sure why that didn't work. ugh
I know I can just change the priority and have to active at once, but that makes the screen look all grainy.
Answer by crawman06 · Aug 06, 2021 at 11:47 AM
I think I have the answer, (I assume you already did it seeing as this was a long time ago) I think I had the same problem as you, what I did was, in the Camera Component there is an option to change the "Target Display". So by changing both/all the camera in the seen to the same Display (this will make them acts like there overlapped) by activating and/or deactivating a camera it should show the other one(s). (I hope that helped, I don't really know much about Unity, or coding for that mater)
Your answer
![](https://koobas.hobune.stream/wayback/20220613003333im_/https://answers.unity.com/themes/thub/images/avi.jpg)