Ved Sarkar
Ved Sarkar

Reputation: 261

Unity: Random NavMesh Agent speed C#?

I have Enemy prefab that has navmesh agent. The enemy is controlled by the down give script , how can i have random navmesh agent speed using the give script

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.
    UnityEngine.AI.NavMeshAgent nav;

    void Awake ()
    {
        player = GameObject.FindGameObjectWithTag ("Player").transform;
        playerHealth = player.GetComponent<PlayerHealth>();
        enemyHealth = GetComponent <EnemyHealth> ();
        nav = GetComponent <UnityEngine.AI.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;
        }
    }
}

Upvotes: 0

Views: 1215

Answers (1)

Programmer
Programmer

Reputation: 125455

Get random number with UnityEngine.Random.Range(yourMinf, yourMax5f);.

Assign that number to NavMeshAgent.speed.

For example, the snippet below will assign random speed between 2 and 5.

nav.speed = UnityEngine.Random.Range(2f, 5f);

Just put that inside your if statement. You may also be interested in other variables such as NavMeshAgent.angularSpeed and NavMeshAgent.acceleration

Upvotes: 2

Related Questions