Skip to content

Instantly share code, notes, and snippets.

@iamgabrielma
Created June 16, 2019 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamgabrielma/38379f8025749c6760a42a5ae0d99581 to your computer and use it in GitHub Desktop.
Save iamgabrielma/38379f8025749c6760a42a5ae0d99581 to your computer and use it in GitHub Desktop.
Attaches the main camera to the player so it moves with the player.
/* The main problem we try to solve here is that the Main Camera is a game object that is already in place before the Player Entity is generated, so it cannot be assigned as the Player instance is null */
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target; // The Player Transform
private bool isPlayerFound;
void Start()
{
isPlayerFound = false; // Will be false by default as the Camera is already in the Inspector before the Player Entity is instantiated.
}
private void Update()
{
if (target != null)
{
return; // If the Player has been found means that its Transform != null, so we can get out of the statement
}
else if (target == null && isPlayerFound == false)
{
target = GameObject.FindWithTag("Player").transform; // Find the Player
gameObject.transform.SetParent(target); // Assign the camera game object as a child of the Player Transform
isPlayerFound = true; // Switch the bool so this is not triggered again
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment