Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Resolved how to make enemy go to points in array in order and not randomly?

Discussion in 'Scripting' started by cowsharts, Mar 31, 2023.

  1. cowsharts

    cowsharts

    Joined:
    Dec 16, 2022
    Posts:
    8
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.AI;
    5.  
    6. public class SWATwalking : StateMachineBehaviour
    7.  
    8. {
    9.     float SWATwalkingtime;
    10.     NavMeshAgent SWATagent01;
    11.  
    12.      private GameObject[] SWATwaypointsAC;
    13.  
    14.     // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
    15.     override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    16.     {
    17.         SWATwalkingtime = 0f;
    18.  
    19.         if(SWATwaypointsAC == null)
    20.         {
    21.             SWATwaypointsAC = animator.gameObject.GetComponent<SWATwaypoints>().SWATwaypoints01;
    22.         }
    23.  
    24.         SWATagent01 = animator.GetComponent<NavMeshAgent>();
    25.  
    26.         SWATagent01.SetDestination(SWATwaypointsAC[Random.Range(0, SWATwaypointsAC.Length)].transform.position);
    27.     }
    28.  
    29.     // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
    30.     override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    31.     {
    32.         SWATwalkingtime += Time.deltaTime;
    33.  
    34.         if (SWATwalkingtime >= 5)
    35.         {
    36.             animator.SetBool("IsWalking", false);
    37.         }
    38.     }
    39.  
    40.  
    41. }

    line 26 is what i need to change, enemy patrols randomly between the four objects in the ray but i want the enemy to move between points in order eg 0, 1, 2, 3 and not randomly but idk how to set the range :)
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,554
    Just keep an
    int currentIndex
    and add 1 to it each time you need to go to the next waypoint. Wrap around to 0 when you reach the end (using
    %
    or an if statement)
     
    Kurt-Dekker likes this.
  3. cowsharts

    cowsharts

    Joined:
    Dec 16, 2022
    Posts:
    8
    thank you!! :)