Unity camera follows player script
13,079
Making the camera following the player is quite straight forward.
Add this script to your main camera. Drag the reference of the player object to the script and then you are done.
You can change the values in the Vector 3 depending on how far you want the camera to be from the player.
using UnityEngine;
public class Follow_player : MonoBehaviour {
public Transform player;
// Update is called once per frame
void Update () {
transform.position = player.transform.position + new Vector3(0, 1, -5);
}
}
Related videos on Youtube
Author by
Ziv Sion
Updated on June 04, 2022Comments
-
Ziv Sion almost 2 years
I'm pretty new to Unity. I tried to create a script that the camera would follow the actor (with a little difference). Is there a way to improve the code? It works just fine. But I wonder if I did it the best way. I want to do it about as I wrote, so if you have any tips. Thank you
Maybe change
Update
toFixedUpdate
?public GameObject player; // Start is called before the first frame update void Start() { player = GameObject.Find("Cube"); // The player } // Update is called once per frame void Update() { transform.position = new Vector3(player.transform.position.x, player.transform.position.y + 5, player.transform.position.z - 10); }
-
komorra about 3 yearsIs simply attaching the camera as a child of "Cube" in the hierarchy wouldn't be sufficient? (in given position 0,5,-10, without any script doing transform changes by frame) ?
-
Ziv Sion about 3 yearsI know that I can do this. I want to do it with a code
-