Dennis Hackethal’s Blog

My blog about philosophy, coding, and anything else that interests me.

Camera Not Showing Anything in Unity 2D? Try This Simple Fix.

Published · revised · 1-minute read · 1 revision

While practicing my Unity game-development skills, I tried getting the camera to follow the player’s y coordinate in a 2D game. I followed this tutorial to do so.

The task seemed simple enough: assign the player’s transform as a serialized field to the camera and use it to set the camera’s position.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Camera : MonoBehaviour
{
    [SerializeField] Transform target;

    void LateUpdate()
    {
        transform.position = new Vector2(
            transform.position.x,
            target.transform.position.y
        );
    }
}

In this script, target represents the player object’s transform component, assigned in the Unity editor by dragging the player game object into the corresponding field. The camera’s x coordinate is retained, and the player’s y coordinate is used to set the camera’s y coordinate. This way, the camera follows the player up and down but not left or right – but that’s an implementation detail.

However, once I ran the game, I suddenly couldn’t see any of the objects anymore.

The issue lies with my use of Vector2. I used it because I’m in a 2D game. Why would I use Vector3, right?

Well, I noticed in the Unity inspector that, even though it’s a 2D game, the camera’s transform still has a z coordinate for its position. By default, it was set to -10 before I started the game, but the Vector2 assignment in the code above implicitly set that to 0. This caused the camera to be on the same plane as the objects in the game, thus looking ‘behind’ them. This helpful answer on the Unity discussion forum tipped me off.

To fix this issue, instead use a Vector3 that retains the camera’s z coordinate:

void LateUpdate()
{
    transform.position = new Vector3(
        transform.position.x,
        target.transform.position.y
        transform.position.z
    );
}

Now it works like a charm.

Takeaways

I’m a Unity noob, but these are the main things I learned from solving this problem:

  1. It seems that, in Unity, 2D games are just flat pancakes inside a 3D world, and z coordinates still matter.
  2. Therefore, even in a 2D game, transform components still have a z coordinate.
  3. Assigning a 2D vector to a 3D field implicitly sets the z coordinate to 0. It does not retain the original z coordinate.

What people are saying

What are your thoughts?

You are responding to comment #. Clear
Your real name is preferred.
Markdown supported. cmd + enter to comment. You are responsible for what you write. Terms, privacy policy
This small puzzle helps protect the blog against automated spam.

Preview