I have an object meant to represent a player that I’d like to spawn in at runtime. Because it is instantiated at runtime, I’m not sure about how to get the main camera in my scene to follow the instance of the player object.
In a camera script (which is attached to the camera), I have the following:
public Transform cameraTarget // i.e. the player's transform component
public Transform cameraLocation
private int offset = -10;
//...
private void TrackTarget();
{
transform.position = new (cameraTarget.transform.position.x,
cameraTarget.transform.position.y,
cameraTarget.transform.position.z + offset);
}
In a separate game manager script, I’m instantiating the player, then attempting to “assign” the camera to it like so:
public Player player;
public Camera mainCamera;
private void Start()
{
InstancePlayer();
player.transform = mainCamera.cameraTarget;
}
private void Update()
{
if (mainCamera.cameraTarget != null)
{
mainCamera.TrackTarget();
}
}
private void InstancePlayer()
{
Vector2 startLocation = Vector2.zero; // using `Vector2.zero` as a placeholder for now
Instantiate(player, startLocation, Quaternion.identity);
}
Perhaps unsurprisingly, this is not a working solution (or if it is, I’m missing how to implement it properly), so to resummarize the question: how might I make the camera follow my instanced player object?