I want to create bot that follow player.And if are multiple enemies,bot shoot nearest enemy.
Here’s enemy script if that help:
using UnityEngine;
using UnityEngine.AI;
public class Enemy : MonoBehaviour
{
public NavMeshAgent agent;
public Transform player;
public LayerMask whatIsGround, whatIsPlayer;
//Patrolling
public Vector3 walkpoint;
bool walkPointSet;
public float walkpointRange;
//Attacking
public float timeBetweenAttacks;
bool alreadyAttacked;
public GameObject projectile;
//States
public float sightRange, attackRange;
public bool playerinSightRange, playerinAttackRange;
private void Awake()
{
player = GameObject.Find("Player").transform;
agent = GetComponent<NavMeshAgent>();
}
void Update()
{
//Check for sight and attack range
playerinSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
playerinAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!playerinSightRange && !playerinAttackRange) Patrolling();
if (playerinSightRange && !playerinAttackRange) Cheasing();
if (playerinSightRange && playerinAttackRange) Attacking();
}
private void Patrolling()
{
if(!walkPointSet) SearchWalkPoint();
if(walkPointSet)
{
agent.SetDestination(walkpoint);
}
Vector3 distancetoWalkpoint = transform.position - walkpoint;
//Walkpoint reached
if (distancetoWalkpoint.magnitude < 1f)
{
walkPointSet = false;
}
}
private void SearchWalkPoint()
{
//calculate random point in range
float randomZ = Random.Range(-walkpointRange, walkpointRange);
float randomX = Random.Range(-walkpointRange, walkpointRange);
walkpoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
if(Physics.Raycast(walkpoint, -transform.up, 2f, whatIsGround))
{
walkPointSet = true;
}
}
private void Cheasing()
{
agent.SetDestination(player.position);
}
private void Attacking()
{
//Make sure enemy doesn't move
agent.SetDestination(transform.position);
transform.LookAt(player);
if(!alreadyAttacked)
{
//Attack code here
Rigidbody rb= Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>();
rb.AddForce(transform.forward * 32f, ForceMode.Impulse);
Destroy(rb, 0.5f);
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBetweenAttacks);
}
}
private void ResetAttack()
{
alreadyAttacked = false;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, attackRange);
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(transform.position, sightRange);
}
}