Creating Enemy #1

Checked with version: 4.6

-

Difficulty: Beginner

This is part 4 of 10 of the Survival Shooter tutorial, in which you will create the enemy behaviour, including animation, state machines, nav-mesh and code.

Creating Enemy #1

Beginner Survival Shooter tutorial

Transcripts

EnemyMovement

Code snippet

using UnityEngine;
using System.Collections;

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;               // Reference to the nav mesh agent.


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


    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;
        }
    } 
}
private var player : Transform;               // Reference to the player's position.
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.


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


function 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;
    }
}

Related tutorials