- Home /
I am having issues with switching camera views with the imput of a key press in a c# script,Trying to swap cameras views on the input of a key-press in C# using unity engine.
so I've looked at other answers and tried typing code from those answers but I'm still confused where I should, A: attach the "camera swap" script and B: how I would get around the error of MonoBehavior. Also with the cameras I currently have them in a parent-child relationship b/c the create with Code live script for following the car was not working for me.
here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraswap : MonoBehaviour
{
public Camera camera;
public Camera camera2;
// Start is called before the first frame update
void Start()
{
camera.enabled = true;
camera2.enabled = false;
}
// Update is called once per frame
void Update()
{
//This will toggle the enabled state of the two cameras between true and false each time
if (Input.GetKeyUp(KeyCode.Return))
{
camera.enabled = !camera.enabled;
camera2.enabled = !camera2.enabled;
}
}
}
Answer by Namey5 · Apr 02, 2020 at 12:47 AM
You can attach this script anywhere. Just drag each of your cameras into the camera slots and it should work when you push the enter key.
Answer by GrayLightGames · Apr 02, 2020 at 01:04 AM
Organization-wise, it may be good to create an empty GameObject somewhere in your hierarchy, call it Camera Swapper or Camera Controller, and put the script there. I have an empty parent object where I put all my controller scripts to keep them organized and easy to find, but you can organize according to your preferences. What did you mean by "the error of MonoBehavior?"