Created
June 16, 2019 14:01
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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