Created
October 27, 2023 20:51
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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