- Home /
Script to make Camera follow the player C#
Hello, why does my script for the camera not work? I want it to follow the player, and I thought, theoretically it should. Here's my code for the Main Cam.
using UnityEngine;
using System.Collections;
public class CamControls : PlayerControl {
void Update () {
transform.position = new Vector3 (xPos, yPos, zPos);
}
}
It inherits from my PlayerControl script that determins xPos, yPos and zPos:
xPos = transform.position.x;
yPos = transform.position.y;
zPos = transform.position.z;
From my understanding of my camera script, it should move where the player currently is. Sorry if this is a silly question, but having an answer to this would help me learn c# more. Thanks!
The playerControl-Class may have the variables, but where are the variables set to any value? Show the playerControl-Class.
Answer by Dlonyar · Jul 02, 2015 at 11:30 AM
You could just make the MainCamera object a child of the player object.
Answer by $$anonymous$$ · Oct 24, 2015 at 01:31 PM
There are two possible problems making a camera the child of the player object. One, if your player is destroyed, the camera is destroyed. Second, if this occurs it will lock up the game and if you have such as a GameController where it has a gameOver function, if the character/player is destroyed, with the camera, it will lock down the game and potentially crash it.
One example of a possible script might be present in the old Project Stealth tutorial.
Answer by TrickyHandz · Oct 24, 2015 at 04:29 AM
Inheriting from the PlayerControl class will not link an instance of the CameraControl class to an instance of the base class. Inheritance simply means that the CamControls class has all the properties and methods of the PlayerControl class. You would still need to assign references to the player object in your game for the camera to execute follow behaviors.
In reference to inheritance in C#, I would recommend reading over the MSDN Article on the subject: Inheritance (C# Programming)
Regarding camera follow behaviors, I recommend this tutorial to get started with 3rd Person Cameras (Note it is from 2012, but is still very informative)