Follow Camera 3D Player

I have camera follow script. But when I attached this script to player, camera doesnt follow the camera. Help me please :slight_smile: thank you

Regards,
Tio.


public Camera mainCamera;

void Start(){
	mainCamera = GameObject.FindWithTag ("MainCamera").camera;
}

void Update () {
	
	mainCamera.transform.position = new Vector3 
		(transform.position.x, 1, -1);
}

I am not sure what you meant to do. In many cases, it is required that the camera will follow the player.

Here’s a sample script (actually taken from Unity’s 2D project sample):

using UnityEngine;
using System.Collections;

    public class FollowPlayer : MonoBehaviour
    {   	
    	private Transform player;		// Reference to the player.
    
    	void Awake ()
    	{
    		// Setting up the reference.
    		player = GameObject.FindGameObjectWithTag("Player").transform;
    	}
    
    	void Update ()
    	{
    		// Set the position to the player's position with the offset.
    		transform.position = player.position;
    	}
    }

This, when attached to the camera, will follow the player’s movement.

Use LateUpdate for this. LateUpdate is called after all Update functions on alle GameObjects have been called. So you make sure, that the camera is updated after all other movement has occured.

Furthermore check if you got the reference for the camera right. You could for easier access just use Camera.main for the first active camera.

void LateUpdate () {
    Camera.main.transform.position = new Vector3 
       (transform.position.x, 1, -1);
}