Help Needed: Fixing ThornAI Script (thorn is the enemy)

Hello everyone,

I’m currently working on a project in Unity and I’m having some trouble with my ThornAI script. The script is supposed to control the behavior of an AI character named Thorn, including patrolling, chasing the player when within a certain distance, and reacting to sounds.

However, I’ve encountered several issues with the script, including problems with pathfinding, errors related to setting destinations for the NavMeshAgent, and difficulty in getting the NavMeshAgent to cover Thorn properly.
Only hearimg works, chasing and patrolling however don’t

I’ve tried troubleshooting on my own, but I haven’t been able to resolve these issues. I would greatly appreciate it if someone could take a look at my code and help me identify and fix any mistakes or errors.

Here’s the ThornAI script I’m currently using:

using UnityEngine;
using UnityEngine.AI;

public class ThornAI : MonoBehaviour
{
    public float patrolSpeed = 3f;
    public float chaseSpeed = 5f;
    public float hearDistance = 10f;
    public LayerMask obstacleMask;

    private Transform player;
    private Vector3 targetPosition;
    private bool isChasing = false;
    private NavMeshAgent navMeshAgent;

    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player").transform;
        targetPosition = GetRandomPosition();
        navMeshAgent = GetComponent<NavMeshAgent>(); // Get the NavMeshAgent component
    }

    void Update()
    {
        if (navMeshAgent == null || !navMeshAgent.enabled) return; // Check if NavMeshAgent is null or disabled

        Patrol();
        Hear();
        if (isChasing)
        {
            Chase();
        }
    }

    void Patrol()
    {
        if (Vector3.Distance(transform.position, targetPosition) < 0.1f)
        {
            targetPosition = GetRandomPosition();
        }

        if (navMeshAgent.enabled) // Ensure NavMeshAgent is enabled before setting destination
        {
            navMeshAgent.SetDestination(targetPosition); // Use NavMeshAgent's SetDestination method
        }
    }

    void Hear()
    {
        if (Vector3.Distance(transform.position, player.position) <= hearDistance)
        {
            targetPosition = player.position;
            isChasing = true;
        }
        else
        {
            isChasing = false;
        }
    }

    void Chase()
    {
        if (navMeshAgent.enabled) // Ensure NavMeshAgent is enabled before setting destination
        {
            navMeshAgent.SetDestination(player.position); // Use NavMeshAgent's SetDestination method
        }
    }

    Vector3 GetRandomPosition()
    {
        const int maxAttempts = 20; // Increase maxAttempts for a larger search area
        int attempts = 0;

        while (attempts < maxAttempts)
        {
            float randomX = Random.Range(-20f, 20f); // Increase search range
            float randomZ = Random.Range(-20f, 20f); // Increase search range
            Vector3 randomPosition = transform.position + new Vector3(randomX, 0f, randomZ);
            UnityEngine.AI.NavMeshHit hit;

            if (UnityEngine.AI.NavMesh.SamplePosition(randomPosition, out hit, 10f, obstacleMask)) // Increase search radius
            {
                return hit.position;
            }

            attempts++;
        }

        Debug.LogWarning("Failed to find a valid position after " + maxAttempts + " attempts. Returning fallback position.");
        return transform.position; // Return current position as fallback
    }
}

Any suggestions, insights, or corrections would be incredibly helpful. Thank you in advance for your assistance!

Code like this won’t (generally) be fixed by staring at it. Instead you must debug it yourself.

By debugging you can find out exactly what your program is doing so you can fix it.

A good first start is to add lots of Debug.Log() logging. If you prefer to use the debugger, here’s how:

Use the above techniques to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.