How to switch between four characters when a button is pressed?

I am making a game with four characters with one camera attached to each of them. when I press the z button, I want to switch to the next camera and enable “player controller”, a component in each of the characters, but only enable it for the character the active camera is attached to

You should be able to do something like: Camera.main.enabled = false; camera.enabled = true; On a script attached to the game object with the camera you want to enable.

1 Answer

1

Since you have 4 of them, you want to setup a round-robin that toggles the “enabled” state of each camera accordingly. So, in a script, in the Update() function, check for the ‘z’ key like this. I just tested this script by attaching it to an empty object I added to my scene, and I added 4 cameras to the scene. Be sure to import Collections.Generic for List or just use arrays. You also might want to toggle/disable the audio-listeners as well since Unity will complain about there being multiple.

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

public class CamSwitcher : MonoBehaviour {

	// Private monobehavior members
	int currentCameraIndex;
	List<Camera> characterCameras;
	
	void Start()
	{
		characterCameras = new List<Camera>();
		/// Get the cameras from the scene using Find or as a Parameter
		Camera camera1 = GameObject.Find("Camera1").camera;
		characterCameras.Add(camera1);
		Camera camera2 = GameObject.Find("Camera2").camera;
		characterCameras.Add(camera2);
		Camera camera3 = GameObject.Find("Camera3").camera;
		characterCameras.Add(camera3);
		Camera camera4 = GameObject.Find("Camera4").camera;
		characterCameras.Add(camera4);
	}
	
	
	void Update()
	{
		if(Input.GetKeyUp(KeyCode.Z))
		{
			// Increment the camera index to the next camera in the list
			currentCameraIndex++;
			if(characterCameras.Count == currentCameraIndex)
			{
				currentCameraIndex = 0;
			}
			
			// loop over the camera list, disabling all but the chosen index
			foreach(Camera camera in characterCameras)
			{
				if(camera == characterCameras[currentCameraIndex])
				{
					camera.enabled = true;
				}
				else
				{
					camera.enabled = false;
				}
			}
		}
	}
 }

thanks! One question, do I have to change any variables in your script and what do I add the script to?

I'll edit my answer with a little more description. You could attach it to almost anything that will be alive in the scene, but what I do is make an Empty gameobject and add the script to that, from the editor.