I’m following a Unity Tutorial on a shooter game, “Survival Shooter Tutorial.” The code “GameObject.FindGameObjectWithTag(“Player”);” Was not working correctly so I made it a public variable and “linked it” to the player. Now I am trying to access the player’s health script’s variable Current Health, but I get errors saying It is not there, even though the hierarchy shows it does. Whilst typing in the way to the variable, It was recommending the object It says is not there. Please don’t rage at me If I did something stupid, because I am a beginner with C-Sharp!
Code:
using UnityEngine;
using System.Collections;
public class EnemyMovement : MonoBehaviour
{
public GameObject player;
PlayerHealth playerHealth;
EnemyHealth enemyHealth;
NavMeshAgent nav;
void Awake ()
{
//player = GameObject.FindGameObjectWithTag ("Player");
playerHealth = player.GetComponent <PlayerHealth> ();
enemyHealth = GetComponent <EnemyHealth> ();
nav = GetComponent <NavMeshAgent> ();
}
void Update ()
{
if (player != null && playerHealth != null)
{
if (enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
{
nav.SetDestination(player.transform.position);
}
else
{
nav.enabled = false;
}
}
}
}
hierarchy and inspector:
If you need more info please let me know!