Skip to content

Instantly share code, notes, and snippets.

@TheMehranKhan
Created October 27, 2023 20:51
Show Gist options
  • Save TheMehranKhan/634f2463baf944e79d6627204d497c2b to your computer and use it in GitHub Desktop.
Save TheMehranKhan/634f2463baf944e79d6627204d497c2b to your computer and use it in GitHub Desktop.
This code block provides a basic enemy AI functionality in Unity. It allows the enemy to follow and attack the player.
/*
Author: themehrankhan
License: MIT License
Description:
This code block provides a basic enemy AI functionality in Unity. It allows the enemy to follow and attack the player.
Usage:
1. Attach this script to the enemy object in Unity.
2. Set the player object in the inspector.
*/
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
public Transform player; // Player object
public float detectionRange = 10f; // Range for detecting the player
public float attackRange = 2f; // Range for attacking the player
private NavMeshAgent agent;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
float distance = Vector3.Distance(transform.position, player.position);
if (distance <= detectionRange && distance > attackRange)
{
agent.SetDestination(player.position);
}
else if (distance <= attackRange)
{
AttackPlayer();
}
}
private void AttackPlayer()
{
// Implement attack logic here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment