Destroying Enemies

版本检查: 5.3

-

难度: 中级

While the enemies can be shot by bullets and their health goes down, enemies should be destroyed when their health reaches zero.

To do this, we will need to adjust the Health script to take into account the difference between players and enemies. The easiest way to do this is with a check box for Destroy On Death.

  • Open the Health script for editing.
  • Add a public field for the Destroy On Death check.
public bool destroyOnDeath;

  • In TakeDamage, check Destroy On Death when Current Health reaches 0 before respawning.
if (destroyOnDeath)
{
            Destroy(gameObject);
} 
else
{
          // existing Respawn code      
}

The final Health Script should look like this:

Health

Code snippet

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;

public class Health : NetworkBehaviour {

    public const int maxHealth = 100;

    public bool destroyOnDeath;

    [SyncVar(hook = "OnChangeHealth")]
    public int currentHealth = maxHealth;

    public RectTransform healthBar;

    public void TakeDamage(int amount)
    {
        if (!isServer)
            return;
        
        currentHealth -= amount;
        if (currentHealth <= 0)
        {
            if (destroyOnDeath)
            {
                Destroy(gameObject);
            } 
            else
            {
                currentHealth = maxHealth;

                // called on the Server, will be invoked on the Clients
                RpcRespawn();
            }
        }
    }

    void OnChangeHealth (int currentHealth)
    {
        healthBar.sizeDelta = new Vector2(currentHealth, healthBar.sizeDelta.y);
    }

    [ClientRpc]
    void RpcRespawn()
    {        if (isLocalPlayer)
        {
            // Set the player’s position to origin
            transform.position = Vector3.zero;
        }
    }
}
  • Save the script.
  • Return to Unity.
  • Select the Enemy prefab from the Project Window.
  • With the Enemy prefab selected,
  • ... set the Destroy On Death checkbox to true.

description

  • Save the Project.

Test the recent changes:

  • Build and Run this scene as a standalone application.
  • Click the Host button from the in-game UI to start this game as a Host.
  • Move the player GameObject.
  • Return to Unity.
  • Enter Play Mode.
  • Click the LAN Client button from the in-game UI to connect to the Host as a Client.

Shooting the enemies will cause them to lose health and when their health reaches zero, the enemies will be destroyed. The players, however, should retain the existing behaviour where they are moved back to the origin point when they “killed”, with their health restored to maximum.

  • Close the standalone player.
  • Return to Unity.
  • Exit Play Mode.