Variable not being assigned
I'm new, and I'm trying to get an enemy to target the nearest object with the "Player" tag and move to it, but Unity keeps telling me that the variable "target" (the player) has not been assigned, when it clearly has been on line 33. I've been fiddling with this code for a while, and for all I know I've just made it worse, but I really need help. Here's the full code:
private var playerHealth : PlayerHealth; // Reference to the player's health.
private var enemyHealth : EnemyHealth; // Reference to this enemy's health.
private var nav : NavMeshAgent; // Reference to the nav mesh agent.
var target : Transform;
function Awake ()
{
// Set up the references.
playerHealth = target.GetComponent (PlayerHealth);
enemyHealth = GetComponent (EnemyHealth);
nav = GetComponent (NavMeshAgent);
}
function Update()
{
var objectsWithTag = GameObject.FindGameObjectsWithTag("Player");
var closestObject : GameObject;
for (var obj : GameObject in objectsWithTag)
{
if(!closestObject)
{
closestObject = obj;
}
//compares distances
if(Vector3.Distance(transform.position, obj.transform.position) <= Vector3.Distance(transform.position, closestObject.transform.position))
{
closestObject = obj;
}
}
target = closestObject.transform;
// If the enemy and the player have health left...
if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
{
// ... set the destination of the nav mesh agent to the player.
nav.SetDestination (target.position);
}
// Otherwise...
else
{
// ... disable the nav mesh agent.
nav.enabled = false;
}
}
i hop this work
public var target : Transform;
attach the player object in hierarchy to this script
Unfortunately, making the variable public didn't help, and I can't attach this script to the player because this script is meant for enemies to find and follow the nearest player. Thanks, though.
@CatinBag987 don't attach this script to the player just attach the player game object to this script by clicking the enemy object & in the Inspector find this script you will see empty filed says Transform drag and drop the player object in this filed .