Untitled

 avatar
unknown
plain_text
25 days ago
4.9 kB
3
Indexable
write a script for unity game engine using c# that gives a character artificial intelligence by patrollinh an area and atracking enemies and detecting them

ChatGPT said:
ChatGPT
Below is a C# script for Unity that provides a character with basic artificial intelligence to patrol a predefined area, detect enemies, and attack them when they are in range.

Unity Script: AIController.cs
csharp
Copy code
using UnityEngine;
using UnityEngine.AI;

public class AIController : MonoBehaviour
{
    public Transform[] patrolPoints; // Waypoints for patrolling
    public float detectionRadius = 10f; // Radius to detect enemies
    public float attackRange = 2f; // Range to attack enemies
    public float attackCooldown = 1.5f; // Time between attacks
    public int damage = 10; // Damage dealt to enemies

    private NavMeshAgent agent; // For movement
    private Transform target; // The detected enemy
    private int currentPatrolIndex = 0;
    private float lastAttackTime;

    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        GoToNextPatrolPoint();
    }

    void Update()
    {
        // Patrol behavior if no target
        if (target == null)
        {
            Patrol();
        }
        else
        {
            ChaseAndAttack();
        }

        // Detect enemies within the detection radius
        DetectEnemies();
    }

    void Patrol()
    {
        // Move to the next patrol point if close to the current one
        if (!agent.pathPending && agent.remainingDistance < 0.5f)
        {
            GoToNextPatrolPoint();
        }
    }

    void GoToNextPatrolPoint()
    {
        if (patrolPoints.Length == 0)
            return;

        agent.destination = patrolPoints[currentPatrolIndex].position;
        currentPatrolIndex = (currentPatrolIndex + 1) % patrolPoints.Length;
    }

    void DetectEnemies()
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, detectionRadius);
        foreach (Collider collider in colliders)
        {
            if (collider.CompareTag("Enemy"))
            {
                target = collider.transform;
                break;
            }
        }
    }

    void ChaseAndAttack()
    {
        // Chase the target
        float distanceToTarget = Vector3.Distance(transform.position, target.position);

        if (distanceToTarget > attackRange)
        {
            agent.destination = target.position;
        }
        else
        {
            // Attack the target
            agent.isStopped = true;

            if (Time.time - lastAttackTime > attackCooldown)
            {
                Attack();
                lastAttackTime = Time.time;
            }
        }
    }

    void Attack()
    {
        // Attack logic, e.g., reducing health of the enemy
        Debug.Log("Attacking " + target.name);

        EnemyHealth enemyHealth = target.GetComponent<EnemyHealth>();
        if (enemyHealth != null)
        {
            enemyHealth.TakeDamage(damage);
        }
    }

    private void OnDrawGizmosSelected()
    {
        // Visualize detection and attack ranges in the editor
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, detectionRadius);

        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, attackRange);
    }
}
Explanation:
Patrolling:

The AI moves between the specified patrolPoints.
It cycles through the waypoints in the array.
Enemy Detection:

Uses Physics.OverlapSphere to find enemies within the detectionRadius.
Enemies must have the tag Enemy to be detected.
Chasing and Attacking:

If an enemy is detected, the AI chases it using the NavMeshAgent.
When the enemy is within the attackRange, the AI stops moving and attacks.
Attack Logic:

The Attack function applies damage to the detected enemy.
The enemy must have a script, e.g., EnemyHealth, with a TakeDamage method.
Visualization:

The OnDrawGizmosSelected method helps visualize the detection and attack ranges in the Unity Editor.
Requirements:
Add this script to a GameObject with a NavMeshAgent component.
Ensure the "Enemy" objects have a collider and are tagged as "Enemy."
Create an EnemyHealth script to manage enemy health.
Example EnemyHealth Script:
csharp
Copy code
using UnityEngine;

public class EnemyHealth : MonoBehaviour
{
    public int health = 50;

    public void TakeDamage(int damage)
    {
        health -= damage;
        Debug.Log(name + " took " + damage + " damage. Remaining health: " + health);

        if (health <= 0)
        {
            Die();
        }
    }

    void Die()
    {
        Debug.Log(name + " has died.");
        Destroy(gameObject);
    }
}
This script provides a basic yet expandable AI system for patrolling, detecting, and attacking enemies. You can tweak it further for more complex behaviors.






Leave a Comment