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.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

detect enemy when seen

Discussion in 'Editor & General Support' started by whycantipickaname, Jun 14, 2020.

  1. whycantipickaname

    whycantipickaname

    Joined:
    Feb 21, 2020
    Posts:
    14
    so i have this script for random movement of ai
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class WanderingAI : MonoBehaviour
    5. {
    6.  
    7.     public float wanderRadius;
    8.     public float wanderTimer;
    9.  
    10.     private Transform target;
    11.     private UnityEngine.AI.NavMeshAgent agent;
    12.     private float timer;
    13.  
    14.     // Use this for initialization
    15.     void OnEnable()
    16.     {
    17.         agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
    18.         timer = wanderTimer;
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void Update()
    23.     {
    24.         timer += Time.deltaTime;
    25.  
    26.         if (timer >= wanderTimer)
    27.         {
    28.             Vector3 newPos = RandomNavSphere(transform.position, wanderRadius, -1);
    29.             agent.SetDestination(newPos);
    30.             timer = 0;
    31.         }
    32.     }
    33.  
    34.     public static Vector3 RandomNavSphere(Vector3 origin, float dist, int layermask)
    35.     {
    36.         Vector3 randDirection = Random.insideUnitSphere * dist;
    37.  
    38.         randDirection += origin;
    39.  
    40.         UnityEngine.AI.NavMeshHit navHit;
    41.  
    42.         UnityEngine.AI.NavMesh.SamplePosition(randDirection, out navHit, dist, layermask);
    43.  
    44.         return navHit.position;
    45.     }
    46. }
    and i was wondering if i could add a player detection to it so if i get within a trigger or somthing it detects the player and goes in that direction
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Yep, add a trigger collider of the appropriate size and shape on a child object of the enemy and add an OnTriggerEnter to your script.
     
  3. whycantipickaname

    whycantipickaname

    Joined:
    Feb 21, 2020
    Posts:
    14
    ight thx but is there a way to disable the random movement script while inside the trigger
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Sure make a boolean variable that you set to true when the enemy sees the player. Use that variable to decide which movement behavior to run with an if statement.
     
  5. whycantipickaname

    whycantipickaname

    Joined:
    Feb 21, 2020
    Posts:
    14
    ight thx