How to get the camera to follow a prefab?

Hiya Unity CommUnity!

I’m writing a script to spawn my player prefab whenever I load a new scene. (I may or may not be doing spawning entirely wrong. Would appreciate input if you have any.)

In any case, I’m trying to get the Main Camera to search for a Player prefab through code and follow that, but what I’m writing is not working and I don’t quite have enough experience yet to figure out why. Here is the relevant code:

var player : Transform;

function Update(){
	if (player == null){
		var player : GameObject = GameObject.FindGameObjectsWithTag("Player")[0];
	}
	Debug.Log(player);
}

The Debug.Log prints out ‘null’ once (which is odd; I would expect it to print out over and over again, being in the Update function), so I’m sure that everything is being called correctly. Do you know what’s wrong with this code?

Any feedback is appreciated. Thanks a lot!

@rainbowparadoxes: You might like check this out: Movement Basics - Unity Learn
One important thing they said here is that you should use LateUpdate() instead of Update() for camera following behavior since it is called after all other objects are updated so you ensure the right update for the camera.

You are only seeing Debug.Log once because Unity nests the same Logs by default. You can expand the single log line to see every line.

For the problem you’re having however, I believe there may be a better way to go about such a problem. Below is the code I am currently using on my camera object in my current prototype.

public Transform target;
public int distance = -10;

void Update () 
{
  this.transform.position = new Vector3 (target.transform.position.x, target.transform.position.y,    distance);
}

In the editor I can set my PlayerPrefab’s transform as the target and have it follow that. This reduces some load at Startup. (Be aware, the above is C# and will differ if your implementing in JS or Boo)

If you’re set on your previous way, than I would suggest double checking that your Player prefab actually has the tag of “Player”. Make sure it’s exact as I’m pretty sure the method is case sensitive.

Also, it may be a little cleaner (if you’re only looking for one player) to use

GameObject.FindWithTag(“Player”);

which will return a single GameObject and remove the unnecessary indexing.