In this article, I will tell you how to implement camera follow script in unity 2d with just few line of code. It is trick in unity 3d but in unity 2d, it is very simple if you are not doing extra camera movement effects. Here is the code that will do character follow by main camera.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MainCameraMovement : MonoBehaviour
{
[SerializeField]
private Transform characterPosition ;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = new Vector3 ( characterPosition.position.x , transform.position.y , transform.position.z );
}
}
In order to use script you need to create empty script and add this code. The next step you will do is add following above code and drag drop script into main camera. It will require game object to which camera should follow. So you will select your desire game object for following character. Look to the below image.
Lets explain coding, first update function is called every frame per second. It regularly check character position if character position is updated then main camera position will also be updated horizontally. The camera is 3d object so it need 3d vector to update main camera position.
That it Thank you.
![]() |
main camera movement script |
![]() |
main camera movement script |
Lets explain coding, first update function is called every frame per second. It regularly check character position if character position is updated then main camera position will also be updated horizontally. The camera is 3d object so it need 3d vector to update main camera position.
That it Thank you.