Hello, I am making a simple 2D game and I am trying to lock the camera to the player using a C# script. The script works when I do not put the positions of the player and camera into Vector3 variables, but when I do the camera does not lock to the player and I do not see any errors appear in the console. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraLock : MonoBehaviour {
public GameObject player;
private Vector3 offset;
private Vector3 cameraPos;
private Vector3 playerPos;
private void Awake()
{
cameraPos = transform.position;
playerPos = player.transform.position;
}
private void Start()
{
offset = cameraPos - playerPos;
}
private void Update()
{
cameraPos = playerPos + offset;
}
}
Can anyone tell me what I am doing wrong? Am I using the wrong variable types for storing the x,y, and z values of the positions? Thanks in advanced.
This should work (I don’t understand why you have the Awake and Start methods, when their content can easily go into the Start only, but it should work) Are you sure you’re placing the script onto the camera? Did you assign the player gameobject to the player variable?
Since cameraPos and playerPos values are assigned in start / awake, they arent updating. Simply assigning them again in the update function would (should) work, or you could do something like this :