Creating an adaptive AI in Unity without using ML-Agents can be done through a variety of methodologies such as finite state machines, behavior trees, or more complex systems like utility AI or GOAP (Goal Oriented Action Planning). Here, I'll provide a simple script that uses the Unity's NavMeshAgent for an AI character that adapts its behavior based on certain stimuli in the environment. This script will not be as advanced as what you could achieve with machine learning through ML-Agents but will illustrate the principles of adaptation.
The following script will make the AI pursue the player when it's within a certain range and lose interest when the player is out of that range. This is a basic example of adaptive behavior:
using UnityEngine;
using UnityEngine.AI;
public class AdaptiveAI : MonoBehaviour
{
public NavMeshAgent agent;
public Transform target; // This should be your player
public float detectionRange = 10f;
public float loseInterestRange = 15f;
private enum State
{
Idle,
Chasing,
Searching
}
private State currentState = State.Idle;
private void Start()
{
if (agent == null)
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
switch (currentState)
{
case State.Idle:
SearchForTarget();
break;
case State.Chasing:
ChaseTarget();
break;
case State.Searching:
SearchForTarget();
break;
}
}
private void SearchForTarget()
{
float distanceToTarget = Vector3.Distance(transform.position, target.position);
if (distanceToTarget <= detectionRange)
{
currentState = State.Chasing;
}
}
private void ChaseTarget()
{
float distanceToTarget = Vector3.Distance(transform.position, target.position);
if (distanceToTarget <= loseInterestRange)
{
agent.SetDestination(target.position);
}
else
{
currentState = State.Searching;
// Here you would implement the logic for the AI to search for the
// target, e.g., move to the last known position, patrol, etc.
// For now, let's just return to the idle state.
currentState = State.Idle;
}
}
}
Attach this script to your AI character and assign a NavMeshAgent component and a target transform. The script represents a simple state machine with three states:
- Idle: The AI is doing nothing or performing idle behavior.
- Chasing: The AI has detected the player and is actively pursuing them.
- Searching: The AI lost the player and is looking for them.
Through these simple states, the AI will pursue the player when they come into a certain range and stop chasing them when they move out of range. You can further modify and extend this behavior to include more complex adaptive logic based on your game's specific requirements.
Remember to set up the environment with a NavMesh for navigation to work and ensure the AI's target is assigned in the inspector or via script. Additionally, you will need to create and bake a NavMesh in your scene for the NavMeshAgent to work correctly.