Search Unity

How do i get my enemies to target a random or nearby player in an array

Discussion in 'Navigation' started by Chris8115, Aug 12, 2016.

  1. Chris8115

    Chris8115

    Joined:
    Jan 19, 2015
    Posts:
    10
    This is my current script, i want the enemy to pick a random or nearby player from an array and move towards them but i can't figure out how to do it.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Linq;
    4.  
    5. public class EnemyMovement : MonoBehaviour
    6. {
    7.  
    8.     Transform player;               // Reference to the player's position.
    9.     PlayerHealth playerHealth;      // Reference to the player's health.
    10.     EnemyHealth enemyHealth;        // Reference to this enemy's health.
    11.     NavMeshAgent nav;               // Reference to the nav mesh agent.
    12.     Animator anim;                    // Reference to the animator
    13.     float MaxDist = 20;
    14.     float MinDist = 1;
    15.  
    16.     void Start ()
    17.     {
    18.         // Set up the references.
    19.  
    20.         player = GameObject.FindGameObjectWithTag ("Player").transform;
    21.         playerHealth = player.GetComponent <PlayerHealth> ();
    22.         enemyHealth = GetComponent <EnemyHealth> ();
    23.         nav = GetComponent <NavMeshAgent> ();
    24.         anim = GetComponent <Animator> ();
    25.     }
    26.        
    27.     void FixedUpdate ()
    28.     {
    29.        
    30.         // If the enemy and the player have health left...
    31.  
    32.         if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
    33.         {
    34.             // ... set the destination of the nav mesh agent to the player.
    35.             if (Vector3.Distance (transform.position, player.position) >= MinDist) {
    36.                
    37.                 nav.SetDestination (player.position);
    38.  
    39.                 anim.SetBool ("Run", true);
    40.             }
    41.         }
    42.     }
    43. }
     
  2. laurentlavigne

    laurentlavigne

    Joined:
    Aug 16, 2012
    Posts:
    6,363