- Home /
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;
}
}
Answer by john-essy · Sep 05, 2017 at 03:54 PM
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);
I'm sorry for being a complete idiot here, but I don't really understand how that will make the camera detect the selected character. Shouldn't I pass the CharacterID to it or something? (CharacterID is the PlayerPrefs I used to store the ID of the selected character)
Also - again, complete beginner here - I got an error: error CS0029: Cannot implicitly convert type UnityEngine.Transform' to
PlayerController' when I tried copying the code you provided.
If this helps in any way, I noticed I get an error saying that the Player Controller script is destroyed (when the game starts) and the Camera Controller is still trying to access it. Is there a way to have the other players destroyed without destroying the Player Controller? Or am I misinterpreting this error?
That is because in update your camera is looking for the player, but when you destroy it, it no longer exists.
What to do is check to see if you have the PlayerController and if you do carry on with your code else return.
Your answer
Follow this Question
Related Questions
Cinemachine glitch 0 Answers
Unity 2D Fighting Game Camera 0 Answers
Help with a 2d camera Controller 1 Answer
Follow camera in 2d game 2 Answers
Keeping UI Element To Game Object When Camera Moves 2 Answers