Ways to Unity 3: Move your Camera with Code
Let’s create a script FollowPlayer.cs
I think MoveCameraDynamically
is more suitable for its name.
attach that script to Main Camera
Just drag your script directly to the Main Camera
that under the hierarchy window. That’s it.
attach your player object to the FollowPlayer
script
We do this because we want to get some information from our player, for example, the location of our player.
Here I used the word
player
, it’s just a reference to the object or character that a human player controls.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
public GameObject player; // this is the public variable that we have declared
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
We do that attachment by dragging the player object to the script variable.
You’ll see the variable inside of the script component that was attached to your Main Camera
object after you have had declared a public variable in the script of FollowPlayer
.
move your camera along with the player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
public GameObject player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = player.transform.position;
}
}
original link
https://yingshaoxo.blogspot.com/2020/11/ways-to-unity-3-move-your-camera-with.html