Hi all, struggling to work out the reason as to why my code is not doing what it does in the tutorial I watched
In the tutorial, he puts the layermasks on the enemy AI called WhatIsPlayer and WhatIsGround; however, they don’t show up as options for mine. I’m fairly sure it’s the reason why my script isn’t working as someone suggested on a previous post.
Any help would be appreciated! Thanks!
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
public NavMeshAgent agent;
public Transform player;
public LayerMask whatIsGround, whatIsPlayer;
//patrolling
public Vector3 walkPoint;
bool walkPointSet;
public float walkPointRange;
//attacking
public float timeBeteenAttacks;
bool alreadyAttacked;
//states
public float sightRange, attackRange;
public bool playerInSightRange, playerInAttackingRange;
private void Awake()
{
player = GameObject.Find("Player").transform;
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
//check for sight and attack range
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
playerInAttackingRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!playerInSightRange && !playerInAttackingRange) Patrolling();
if (playerInSightRange && !playerInAttackingRange) ChasePlayer();
if (playerInAttackingRange && playerInSightRange) AttackPlayer();
}
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 ChasePlayer()
{
agent.SetDestination(player.position);
}
private void AttackPlayer()
{
//make sure enemy doesn't move
agent.SetDestination(transform.position);
transform.LookAt(player);
if (!alreadyAttacked)
{
alreadyAttacked = true;
Invoke(nameof(ResetAttack), timeBeteenAttacks);
}
}
private void ResetAttack()
{
alreadyAttacked = false;
}
}
