Accessing Variable from another script is slow...

Okay so I’m just trying to get an enemy script to read my players health… and stay updated. But after the scripts run for a while my computer starts bogging down (like bad).

I know there is a better way to do this. Not sure how.

Player Script

using UnityEngine;
using System.Collections;

public class PlayerScript : MonoBehaviour {
	public int PlayerHealth = 100;
	public bool PlayerAlive = true;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		InvokeRepeating("PrintHealth",5f,5f);

		if (PlayerHealth <= 0) {
						PlayerAlive = false;
				} else {
						PlayerAlive = true;
				}
	
	}

		 void PrintHealth()
		        {
				print("Players Health is :"+PlayerHealth);
				print("Is Player Alive?  :"+PlayerAlive);
				}
}

Enemy Script

using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour {
	public GameObject Player;
	private int TargetHealth;

	// Use this for initialization
	void Start () {

	}
	
	// Update is called once per frame
	void Update () {
		GameObject thePlayer = GameObject.Find("Player");
		PlayerScript playerScript = Player.GetComponent<PlayerScript>();
		TargetHealth = playerScript.PlayerHealth;

		print("Enemy see's Players Health is :"+TargetHealth);
	
	}
}

GameObject.Find() is slow. You should not use it every frame. If your player can change during game play, tag your player with a tag (like ‘Player’) then use GameObject.FindWithTag().

         GameObject thePlayer = GameObject.FindWithTag("Player");

If the same player object exists during game play, then take it a step further. At the top of the file declare:

    private GameObject thePlayer;

Then in Start() you do:

    thePlayer = GameObject.Find("Player").GetComponent<PlayerScript>();

That way you will not have in GameObject.Find() or GetComponent() calls in Update().