Make the camera follow the players

I have this script from a tutorial on YouTube that makes the camera follow the player. My problem is, I made more than one character, and I want the camera to follow whichever character is selected.

What I did in other scripts: When the player clicks on a character, this character is set active, instantiated in the scene and the other characters are destroyed.

I have thought about making a dynamic array for the characters but couldn’t think of an proper way to do it.

This is the script I’m currently using:

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

	public PlayerController thePlayer;

	private Vector3 lastPlayerPosition;
	private float distanceToMove;

	void Start () {
		thePlayer = FindObjectOfType<PlayerController> ();
			lastPlayerPosition = thePlayer.transform.position;
	}

	void Update () {
			distanceToMove = thePlayer.transform.position.x - lastPlayerPosition.x;
			transform.position = new Vector3 (transform.position.x + distanceToMove, transform.position.y, transform.position.z);
			lastPlayerPosition = thePlayer.transform.position;
	}
}

When you destroy your player you need to give your camera a new target. If i understand correctly you only have one camera.

So when you destroy the player, before you make this call you could do something like Camera.main.gameOBject.GetComponent().thePlayer = myNewPlayer.

Or you could create a method inside your camera script like –

public void SetTarget(Transform tr)
{
       thePlayer = tr.GetComponent<PlayerController>().transform;
}

Then on start of your player controller you could then do

FindObjectOfType<CameraController>().SetTarget(transform);