Hello all,
I’m trying to get code from one of my classes and use it as a global variable. I’ve tried a multitude of things. Here is my current code:
public Health health;
void Awake() {
health = GameObject.FindGameObjectWithTag("Player").GetComponent < Health > ();
if (health) {
Debug.Log("Found Health");
}
else {
Debug.Log("Cannot find Health");
}
}
What I’m trying to do is simple: see if it can find the Health script. However, it cannot find the component. I have attached the script to the player object and put the Health variable set as the Player in the editor. It will always say it cannot find the Health script on the Player object though.
This is the Health script from top to bottom:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//A lot of this is probably useless and me just experimenting with code but I figured I'd put it in //here just in case
public class Health : MonoBehaviour {
public GameObject Phealthbar;
public GameObject Ehealthbar;
public GameObject Ehealthnotify;
public GameObject Phealthnotify;
private int phealth;
public int Phealth {
get {
return phealth;
}
set {
phealth = value;
}
}
private int ehealth;
public int Ehealth {
get {
return ehealth;
}
set {
ehealth = value;
Ehealthbar.GetComponent<Text>().text = "Enemy Health: " + Ehealth.ToString();
}
}
public void TakeHealth(string player, int amount) {
if(player == "Enemy") {
Ehealth -= amount;
Ehealthbar.GetComponent<Text>().text = "Enemy Health: " + Ehealth.ToString();
}
}
}
These are pictures of the editor to show what I mean if I was unclear:

Please let me know if more information is needed. Thank you.
