2D Game Objects Disappearing with Custom Camera Script in Unity 4.3

Tags: Unity3d, 2D, Camera

I was working on my tentatively named "Unity 2D Platformer Starter Kit" (more on this later) which I'll probably use in many projects and game jams in the future, and while implementing a basic camera script a ran into a strange issue. I was making it so that the camera automatically follows the player when the player moves. Turns out I fell into a confusing yet obviously silly pitfall where when the camera script tracked the player, all the game objects disappeared. The good news is that it was a very simple fix once I made sense of the issue.

Long story short, I took the naive approach and simply set my camera's position to the player's position like so:

void Update () 
{
	transform.position = GameObject.Find("Player").transform.position;	
}

 

Fact of the matter was, by doing this I had set the camera's Z position to the same as the rest of the world and if the objects aren't in front of the camera then they simply aren't visible. By retaining the camera's Z position everything works great. Here is the working code:

void Update ()
{
	Vector3 player = GameObject.Find("Player").transform.position;
	transform.position = new Vector3(player.x, player.y, transform.position.z);
}

  

Comments powered by Disqus