Search Unity

Enemy choose a player from array ?

Discussion in 'Scripting' started by Quast, Jan 16, 2020.

  1. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    560
    I'm trying to make my enemy pick a player from array that no enemy around him. Now, if player surrounded with 3 enemies, the rest will select second player closest to them. How to make enemy pick the second player ?

    Code (CSharp):
    1.  
    2. public GameObject[] players;
    3. public GameObject AttackThisPlayer;
    4. public int player_number;
    5. public bool PlayerSurrounded; // script attached to player, if 3 enemies around him it turn True.
    6. public bool attackPlayer = false; // if enemy enter player zone turn true. So the rest will not pick this player.
    7.  
    8. void Start()
    9. {
    10.    players = GameObject.FindGameObjectsWithTag("Player"); // 5 players
    11. }
    12.  
    13. void Update()
    14. {
    15.  
    16.    for (int i = 0; i < player.Length; i++)
    17.    {
    18.        if (Vector3.Distance(transform.position, players[i].transform.position) <
    19.            Vector3.Distance(transform.position, players[player_number].transform.position))
    20.        {
    21.            player_number =  i;
    22.            AttackThisPlayer = players[player_number];
    23.  
    24.        }
    25.    }
    26.  
    27.    PlayerSurrounded = AttackThisPlayer.GetComponentInChildren<enemy_around>().enemiesBool;
    28.  
    29.   }
    30.  
    31.     void OnTriggerEnter(Collider other)
    32.     {
    33.         if (other.transform.CompareTag("Player") )
    34.         {
    35.         attackPlayer = true;
    36.         }
    37.  
    38.     }
    39.  
    40.     void OnTriggerExit(Collider other)
    41.     {
    42.         if (other.transform.CompareTag("Player"))
    43.         {
    44.                 attackPlayer = false;
    45.         }
    46.     }
    47.  
    48. }
    49.