C# TP_Camera Stack Overflow

Hi everyone, I’ve been following 3dbuzz’s tutorial series on how to make a third person controller. I have gotten to making the TP_Camera script.But when I run it my scene is very slow and laggy.I also get a stack overflow warning.Any idea what is wrong with my script?

using UnityEngine;
using System.Collections;

public class TP_Camera : MonoBehaviour {

	public static TP_Camera instance;
	public Transform targetLookAt;
	
	void Awake(){
	instance = this;
	TP_Camera.UseExistingOrCreateNewMainCamera();
	}
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	public static void UseExistingOrCreateNewMainCamera(){
	 GameObject tempCamera;
	 GameObject targetLookAt;
	 TP_Camera  myCamera;
	 
	 if(Camera.mainCamera != null){
	  tempCamera = Camera.mainCamera.gameObject;
		}
		else{
		 tempCamera = new GameObject("Main Camera");
		 tempCamera.AddComponent("Camera");
		 tempCamera.tag = "MainCamera";
		}
		tempCamera.AddComponent("TP_Camera");
		myCamera = tempCamera.GetComponent("TP_Camera") as TP_Camera;
		
		targetLookAt = GameObject.Find("targetLookAt") as GameObject;
		
		if(targetLookAt == null){
		targetLookAt = new GameObject("targetLookAt");
		targetLookAt.transform.position = Vector3.zero;
		}
		myCamera.targetLookAt = targetLookAt.transform;
		
	}
}

The problem is that your code has an endless loop. When Awake is called, it calls UseExistingOrCreateNewMainCamera(). This then calls tempCamera.AddComponent(“TP_Camera”), which adds the script to the camera object, and leads to Awake() being called again.

One simple way to fix this would be to add a static bool, and then reference that in Awake, like so:

    static bool initialized = false;
	
    void Awake()
	{		
		if (!initialized)
		{
			initialized = true;
	    	instance = this;
	    	TP_Camera.UseExistingOrCreateNewMainCamera();
		}
    }