0
votes

I am building a multiplayer game using unity's survival shooter asset, the player is prefab spawned using network manager in the scene and has tag Player.The enemies are spawned and managed by Enemy Manager that searches for the Player tag and makes enemy target the player,but the enemy only attack the player which is spawned 1st and does not attack the players spawned afterwards.

EnemyManager Script

public class EnemyManager : MonoBehaviour
{
    PlayerHealth playerHealth;       // Reference to the player's heatlh.
    public GameObject enemy;                // The enemy prefab to be spawned.
    public float spawnTime = 3f;            // How long between each spawn.
    public Transform[] spawnPoints;         // An array of the spawn points this enemy can spawn from.


    void Start ()
    {
        // Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
        playerHealth = GameObject.FindWithTag("Player").GetComponent<PlayerHealth>();
        InvokeRepeating ("Spawn", spawnTime, spawnTime);
    }


    void Spawn ()
    {
        // If the player has no health left...
        if(playerHealth.currentHealth <= 0f)
        {
            // ... exit the function.
            return;
        }

        // Find a random index between zero and one less than the number of spawn points.
        int spawnPointIndex = Random.Range (0, spawnPoints.Length);

        // Create an instance of the enemy prefab at the randomly selected spawn point's position and rotation.
        Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
    }
}

Enemy Attack Script

public class EnemyAttack : MonoBehaviour
{
    public float timeBetweenAttacks = 0.5f;     // The time in seconds between each attack.
    public int attackDamage = 10;               // The amount of health taken away per attack.


    Animator anim;                              // Reference to the animator component.
    GameObject player;                          // Reference to the player GameObject.
    PlayerHealth playerHealth;                  // Reference to the player's health.
    EnemyHealth enemyHealth;                    // Reference to this enemy's health.
    bool playerInRange;                         // Whether player is within the trigger collider and can be attacked.
    float timer;                                // Timer for counting up to the next attack.


    void Awake ()
    {
        // Setting up the references.
        player = GameObject.FindGameObjectWithTag ("Player");
        playerHealth = player.GetComponent <PlayerHealth> ();
        enemyHealth = GetComponent<EnemyHealth>();
        anim = GetComponent <Animator> ();
    }


    void OnTriggerEnter (Collider other)
    {
        // If the entering collider is the player...
        if(other.gameObject == player)
        {
            // ... the player is in range.
            playerInRange = true;
        }
    }


    void OnTriggerExit (Collider other)
    {
        // If the exiting collider is the player...
        if(other.gameObject == player)
        {
            // ... the player is no longer in range.
            playerInRange = false;
        }
    }


    void Update ()
    {
        // Add the time since Update was last called to the timer.
        timer += Time.deltaTime;

        // If the timer exceeds the time between attacks, the player is in range and this enemy is alive...
        if(timer >= timeBetweenAttacks && playerInRange && enemyHealth.currentHealth > 0)
        {
            // ... attack.
            Attack ();
        }

        // If the player has zero or less health...
        if(playerHealth.currentHealth <= 0)
        {
            // ... tell the animator the player is dead.
            anim.SetTrigger ("PlayerDead");
        }
    }


    void Attack ()
    {
        // Reset the timer.
        timer = 0f;

        // If the player has health to lose...
        if(playerHealth.currentHealth > 0)
        {
            // ... damage the player.
            playerHealth.TakeDamage (attackDamage);
        }
    }
}

Enemy Movement

public class EnemyMovement : MonoBehaviour
{
    Transform player;               // Reference to the player's position.
    PlayerHealth playerHealth;      // Reference to the player's health.
    EnemyHealth enemyHealth;        // Reference to this enemy's health.
    NavMeshAgent nav;

    void Awake ()
    {
        // Set up the references.
        player = GameObject.FindGameObjectWithTag ("Player").transform;
        playerHealth = player.GetComponent<PlayerHealth>();
        enemyHealth = GetComponent <EnemyHealth> ();
        nav = GetComponent <NavMeshAgent> ();
    }


    void Update ()
    {
        // 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 (player.position);
        }
        // Otherwise...
        else
        {
            // ... disable the nav mesh agent.
            nav.enabled = false;
        }
    }
}

Local player Setup Script

public class LocalPlayerSetup : NetworkBehaviour {

    void Start()
    {
        GameObject.FindGameObjectWithTag ("EnemyManager").SetActiveRecursively (true);

        if (isLocalPlayer) {
            GameObject.FindGameObjectWithTag ("MainCamera").GetComponent<CameraFollow> ().enabled = true;
            GetComponent<PlayerMovement> ().enabled = true;
            GetComponentInChildren<PlayerShooting> ().enabled = true;
        }

    }

}

1
Your code snippets don't show the script that shows how the enemy decided which player to attack. Generally, though, the enemy needs to check all the players and decided which one to attack, most usually going after whichever one is the closest.Abion47
No the enemy are only attacking the player 1st spawned.please check now added the enemy attack and movement scriptVed Sarkar
The target is being set with the call to GameObject.FindGameObjectWithTag, which only returns a single object. You can get all the players with instead using GameObject.FindGameObjectsWithTag, and then you can iterate through them to find the closest player. (This assumes that all the player entities have the "Player" tag.)Abion47

1 Answers

0
votes

There are couple of problem in your code:

  1. You are finding player at AWAKE event (which only runs once at start)
  2. You are finding player using FindGameObjectWithTag which only returns one object.
  3. You are spawning enemy without Network Spawn which will not generate enemy on client.

Generic solution to your complex problems:

  1. Make a list of player and Frequently check Players and its count using Invoke repeating. Later, use that list(player list) to attack on player.
  2. Find Player using FindGameObjectsWithTag, it will return a list of player.
  3. Use Network Spawn to generate enemy on all clients.