make a script where theres an entity that just wanders around until it finds the closest tag player to it. when wandering it will play the wandring sound, when chasing it will play the chasing sound. make it a sneeky AI for horror in unity. make it all networked with photon pun use audiosources no audioclips
Assistant
User
} expected
The name 'CheckLostPlayer' does not exist in the current context
The name 'MoveTowards' does not exist in the current context
The name 'ChangeState' does not exist in the current context
The name 'ChangeState' does not exist in the current context
The name 'MoveTowards' does not exist in the current context, and use navmesh
Assistant
User
its not chasing the tag Player, btw the player prefab witht he player tag is in the DoNotDestroy thing
Assistant
User
recode the entire script
Assistant
User
'PlayerManager' is missing the class attribute 'ExtensionOfNativeClass'!
Assistant
Certainly! Below is a Unity C# script that implements a sneaky horror AI entity using Photon PUN for networking. This entity wanders randomly until it finds the closest player with the tag "Player", then chases that player. It plays different looping sounds via AudioSources (no AudioClip assigned in the inspector, so you must assign an AudioClip at runtime or dynamically). It assumes you will set the AudioClip dynamically or via code elsewhere.
Key features:
Uses PhotonView for network synchronization.
Wanders randomly within a radius.
Detects the closest "Player" tagged object.
Switches between wandering and chasing states.
Plays sounds for wandering and chasing by enabling/disabling AudioSources.
AudioSources have no clips assigned by default; you control that in code or elsewhere.
Important Notes:
Make sure your project has Photon PUN 2 imported.
Attach this script to the AI entity prefab with a PhotonView component.
Add two AudioSources to the entity as children or on the same GameObject:
One for wandering sound.
One for chasing sound.
Make sure the AudioSources have loop = true and no AudioClip assigned in the inspector.
Ensure your players have the tag "Player".
csharp
using UnityEngine;
using Photon.Pun;
using System.Collections;
public class SneakyAI : MonoBehaviourPunCallbacks
{
public float wanderRadius = 10f;
public float wanderInterval = 3f;
public float chaseSpeed = 4f;
public float wanderSpeed = 2f;
public float detectionRadius = 15f;
private Vector3 wanderTarget;
private Transform chaseTarget;
private float wanderTimer;
private enum State { Wandering, Chasing };
private State currentState = State.Wandering;
// AudioSources (assigned in inspector or via GetComponents)
private AudioSource wanderingAudioSource;
private AudioSource chasingAudioSource;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
AudioSource[] audioSources = GetComponents<AudioSource>();
if(audioSources.Length < 2)
{
Debug.LogError("SneakyAI requires 2 AudioSources on the same GameObject.");
enabled = false;
return;
}
wanderingAudioSource = audioSources[0];
chasingAudioSource = audioSources[1];
// AudioSources should be set to loop in inspector
wanderingAudioSource.playOnAwake = false;
chasingAudioSource.playOnAwake = false;
wanderTimer = wanderInterval;
// Start playing wandering sound by default
if (wanderingAudioSource.clip != null)
wanderingAudioSource.Play();
}
void Update()
{
// Only run AI logic on the *MasterClient* (server authoritative)
if (!PhotonNetwork.IsMasterClient)
return;
switch (currentState)
{
case State.Wandering:
Wander();
LookForPlayer();
break;
case State.Chasing:
Chase();
CheckLostPlayer();
break;
}
}
void Wander()
{
wanderTimer -= Time.deltaTime;
if (wanderTimer <= 0f)
{
// Pick a new wander position within a radius from current position
Vector3 randomDirection = Random.insideUnitSphere * wanderRadius;
randomDirection.y = 0;
wanderTarget = transform.position + randomDirection;
wanderTimer = wanderInterval;
}
MoveTowards(wanderTarget, wanderSpeed);
}
void LookForPlayer()
{
// Find closest player by tag within detection radius
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
float closestDistance = detectionRadius;
Transform closestPlayer = null;
foreach (var player in players)
{
float dist = Vector3.Distance(transform.position, player.transform.position);
if (dist < closestDistance)
{
closestDistance = dist;
closestPlayer = player.transform;
}
}
if (closestPlayer != null)
{
chaseTarget = closestPlayer;
ChangeState(State.Chasing);
}
}
void Chase()
{
if (chaseTarget == null)
{
ChangeState(State.Wandering);
return;
}
MoveTowards(chaseTarget.position, chaseSpeed);
}
void CheckLostPlayer()
{
if (chaseTarget == null)
{
ChangeState(State.Wandering);
return;
}
float dist = Vector3.Distance(transform.position, chaseTarget.position);
if (dist > detectionRadius * 1.2f) // Some hysteresis to avoid flickering state
{
chaseTarget = null;
ChangeState(State.Wandering);
}
}
void MoveTowards(Vector3 target, float speed)
{
Vector3 direction = (target - transform.position).normalized;
Vector3 move = direction * speed * Time.deltaTime;
// Simple movement ignoring obstacles - can replace with navmesh or pathfinding if needed
rb.MovePosition(transform.position + move);
// Rotate to face target smoothly
if (direction != Vector3.zero)
{
Quaternion toRotation = Quaternion.LookRotation(direction, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, toRotation, 5f * Time.deltaTime);
}
}
void ChangeState(State newState)
{
if (currentState == newState) return;
currentState = newState;
switch(newState)
{
case State.Wandering:
// Stop chasing audio
if (chasingAudioSource.isPlaying)
chasingAudioSource.Stop();
// Play wandering audio if clip is present
if (wanderingAudioSource.clip != null && !wanderingAudioSource.isPlaying)
wanderingAudioSource.Play();
break;
case State.Chasing:
// Stop wandering audio
if (wanderingAudioSource.isPlaying)
wanderingAudioSource.Stop();
// Play chasing audio if clip is present
if (chasingAudioSource.clip != null && !chasingAudioSource.isPlaying)
chasingAudioSource.Play();
break;
}
}
#region Photon Serialization (optional)
// Could implement photon transform synchronization or use a PhotonTransformView component separately.
#endregion
}
How to Use
Setup AI prefab:
Add a Rigidbody (set to kinematic if you want manual movement).
Add a PhotonView component.
Attach 2 AudioSources to the GameObject.
No AudioClip assigned in inspector.
Loop enabled.
Play On Awake disabled.
Attach this SneakyAI script.
At runtime, assign the actual AudioClip you want for wandering and chasing sounds to the respective AudioSources via script or any other method. The script will not try to play if there is no clip.
Players should have the tag "Player".
Networking:
The AI logic runs only on PhotonMasterClient to prevent desync or conflicting movement.
You need to handle transform synchronization with PhotonTransformView or similar.
If you want me to also provide a version that chooses the clips automatically or loads audio dynamically, or to add pathfinding with NavMeshAgent, just ask!
Thanks for the feedback! The errors you mention usually come from missing or misplaced braces {} or method definitions outside the class.
I will rewrite the script using NavMeshAgent and ensure all functions are within the class correctly, and fix syntax issues.
Updated SneakyAI with NavMeshAgent and Photon PUN
Features:
Uses a NavMeshAgent for movement.
Plays wandering sound while wandering, chasing sound while chasing.
Uses Photon PUN; AI logic runs on MasterClient only.
Fixes all missing method errors.
No AudioClip assigned in AudioSource inspector; you assign dynamically or externally.
Players must have tag "Player".
csharp
using UnityEngine;
using UnityEngine.AI;
using Photon.Pun;
[RequireComponent(typeof(NavMeshAgent))]
[RequireComponent(typeof(PhotonView))]
[RequireComponent(typeof(AudioSource))]
public class SneakyAI : MonoBehaviourPunCallbacks
{
[Header("AI Settings")]
public float wanderRadius = 10f;
public float wanderInterval = 3f;
public float detectionRadius = 15f;
public float chaseSpeed = 4f;
public float wanderSpeed = 2f;
private NavMeshAgent agent;
private PhotonView pv;
private float wanderTimer;
private Transform chaseTarget;
private enum State { Wandering, Chasing }
private State currentState = State.Wandering;
[Header("AudioSources")]
// You need to assign these in inspector or get Children AudioSources dynamically
public AudioSource wanderingAudioSource;
public AudioSource chasingAudioSource;
void Start()
{
agent = GetComponent<NavMeshAgent>();
pv = GetComponent<PhotonView>();
if (!wanderingAudioSource || !chasingAudioSource)
{
Debug.LogError("Assign Wandering and Chasing AudioSources in inspector");
enabled = false;
return;
}
wanderTimer = wanderInterval;
// Setup AudioSources properly
wanderingAudioSource.loop = true;
wanderingAudioSource.playOnAwake = false;
chasingAudioSource.loop = true;
chasingAudioSource.playOnAwake = false;
// Start with wandering sound playing if clip is assigned
if (wanderingAudioSource.clip != null)
wanderingAudioSource.Play();
agent.speed = wanderSpeed;
PickNewWanderTarget();
}
void Update()
{
// Run AI logic only on MasterClient
if (!PhotonNetwork.IsMasterClient)
return;
switch (currentState)
{
case State.Wandering:
Wander();
LookForPlayer();
break;
case State.Chasing:
Chase();
CheckLostPlayer();
break;
}
}
private void Wander()
{
wanderTimer -= Time.deltaTime;
if (wanderTimer <= 0f || HasReachedDestination())
{
PickNewWanderTarget();
wanderTimer = wanderInterval;
}
}
private void PickNewWanderTarget()
{
Vector3 randomDirection = Random.insideUnitSphere * wanderRadius;
randomDirection += transform.position;
NavMeshHit navHit;
if (NavMesh.SamplePosition(randomDirection, out navHit, wanderRadius, NavMesh.AllAreas))
{
agent.SetDestination(navHit.position);
}
agent.speed = wanderSpeed;
}
private void LookForPlayer()
{
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
float closestDistance = detectionRadius;
Transform closestPlayer = null;
foreach (var player in players)
{
float dist = Vector3.Distance(transform.position, player.transform.position);
if (dist < closestDistance)
{
closestDistance = dist;
closestPlayer = player.transform;
}
}
if (closestPlayer != null)
{
chaseTarget = closestPlayer;
ChangeState(State.Chasing);
}
}
private void Chase()
{
if (chaseTarget == null)
{
ChangeState(State.Wandering);
return;
}
agent.SetDestination(chaseTarget.position);
agent.speed = chaseSpeed;
}
private void CheckLostPlayer()
{
if (chaseTarget == null)
{
ChangeState(State.Wandering);
return;
}
float dist = Vector3.Distance(transform.position, chaseTarget.position);
if (dist > detectionRadius * 1.2f)
{
chaseTarget = null;
ChangeState(State.Wandering);
}
}
private void ChangeState(State newState)
{
if (currentState == newState)
return;
currentState = newState;
switch (newState)
{
case State.Wandering:
// Stop chasing sound
if (chasingAudioSource.isPlaying)
chasingAudioSource.Stop();
// Play wandering sound
if (wanderingAudioSource.clip != null && !wanderingAudioSource.isPlaying)
wanderingAudioSource.Play();
agent.speed = wanderSpeed;
PickNewWanderTarget();
break;
case State.Chasing:
// Stop wandering sound
if (wanderingAudioSource.isPlaying)
wanderingAudioSource.Stop();
// Play chasing sound
if (chasingAudioSource.clip != null && !chasingAudioSource.isPlaying)
chasingAudioSource.Play();
agent.speed = chaseSpeed;
break;
}
}
private bool HasReachedDestination()
{
if (!agent.pathPending)
{
if (agent.remainingDistance <= agent.stoppingDistance)
{
if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
return true;
}
}
return false;
}
}
How to set up your GameObject:
Add a NavMeshAgent component.
Add a PhotonView component.
Add your two AudioSources (wandering + chasing).
Leave both AudioSources without AudioClip in the inspector.
Enable Loop for both.
Disable Play On Awake.
Assign the two AudioSources to the wanderingAudioSource and chasingAudioSource public fields of the script.
Bake a NavMesh in your scene.
Make sure players have the tag "Player" for detection.
Notes:
This AI only runs logic on MasterClient to avoid desync.
NavMeshAgent handles smooth pathfinding.
Sounds are controlled by enabling/disabling AudioSources.
Audio clips are assigned dynamically by you or can be assigned later before play.
If you want, I can also help you implement AudioClip assignment dynamically or add more networking synchronization for position/rotation!
Thanks for the clarification!
If your player prefab (tagged "Player") is instantiated with DontDestroyOnLoad, the AI in a newly loaded scene may not see those "Player" objects with GameObject.FindGameObjectsWithTag("Player") — especially if they're in a different scene or hierarchy or maybe even on different Photon clients.
Additionally, since this is multiplayer with Photon PUN, the players exist on their clients and are network instantiated (PhotonNetwork.Instantiate) or persistent across scenes, which can complicate the AI's ability to find them by tag.
What could be going wrong:
The AI runs on MasterClient only, but players exist on their own clients, and the "Player" GameObjects may not be present or discoverable on the MasterClient.
GameObject.FindGameObjectsWithTag("Player") only finds active GameObjects in the current scene and hierarchy of the client that executes it.
If players are marked DontDestroyOnLoad but live in a different scene or another root object, or locally on each client only, the AI won't find them.
Solution approach:
Since this is multiplayer, the MasterClient should track players via Photon:
Use PhotonNetwork.PlayerList to get all connected players.
For each player, get their networked avatar or prefab instance (which must be registered).
You can keep track of instantiated player objects on the MasterClient in a list or via a centralized manager.
How to Track Players Correctly in Photon for AI:
Implement a player manager on MasterClient that tracks instantiated player avatars.
Each player prefab on spawn should register itself with the manager (on MasterClient).
Your AI queries the list of active player instances instead of FindGameObjectsWithTag.
A simple way:
Each player prefab, when instantiated, can register itself globally with a static list accessible on MasterClient.
E.g., create a static PlayerManager class with a list of players:
csharp
public static class PlayerManager
{
public static List<Transform> allPlayers = new List<Transform>();
public static void RegisterPlayer(Transform t)
{
if (!allPlayers.Contains(t))
allPlayers.Add(t);
}
public static void UnregisterPlayer(Transform t)
{
if (allPlayers.Contains(t))
allPlayers.Remove(t);
}
}
Then, on your player prefab script, do something like:
csharp
void OnEnable()
{
if (PhotonNetwork.IsMasterClient)
{
PlayerManager.RegisterPlayer(transform);
}
}
void OnDisable()
{
if (PhotonNetwork.IsMasterClient)
{
PlayerManager.UnregisterPlayer(transform);
}
}
Add a simple static PlayerManager class holding a list of active player transforms.
Modify player prefabs to register/unregister on enable/disable only on MasterClient.
AI only uses that list to detect closest player.
Because players are DontDestroyOnLoad, this list will persist and always be accurate (as long as players properly register/unregister).
The AI is still on MasterClient to ensure movement synchronization.
Optional: Registering players automatically via Photon callbacks
Instead of manual register/unregister from player prefabs, you can listen to Photon callbacks on MasterClient:
csharp
public class PlayerTracker : MonoBehaviourPunCallbacks
{
public override void OnPlayerEnteredRoom(Photon.Realtime.Player newPlayer)
{
// This triggers on MasterClient for new players joining
// Could do some logic here if needed
}
public override void OnPlayerLeftRoom(Photon.Realtime.Player otherPlayer)
{
// Remove the player from list if needed
}
}
But since what you need is tracking instantiated player objects (transforms), the simple register/unregister on player scripts is usually easiest.
Full example for PlayerManager:
csharp
using System.Collections.Generic;
using UnityEngine;
public static class PlayerManager
{
public static List<Transform> allPlayers = new List<Transform>();
public static void RegisterPlayer(Transform t)
{
if (!allPlayers.Contains(t))
allPlayers.Add(t);
}
public static void UnregisterPlayer(Transform t)
{
if (allPlayers.Contains(t))
allPlayers.Remove(t);
}
}
Player prefab script snippet example:
csharp
using Photon.Pun;
using UnityEngine;
public class PlayerRegister : MonoBehaviourPunCallbacks
{
void OnEnable()
{
if (PhotonNetwork.IsMasterClient)
{
PlayerManager.RegisterPlayer(transform);
}
}
void OnDisable()
{
if (PhotonNetwork.IsMasterClient)
{
PlayerManager.UnregisterPlayer(transform);
}
}
}
This way:
Your AI code uses PlayerManager's list every frame (or as needed) to detect closest player.
It avoids missing players due to DontDestroyOnLoad or scene loading issues.
If you want me to provide a fully integrated script with all of this included, just let me know!
Absolutely! Below is a fully working Unity script for your sneaky horror AI using Photon PUN 2, NavMeshAgent for movement, and a PlayerManager to track all players correctly across scenes including DontDestroyOnLoad.
How this works:
AI only runs on the MasterClient.
Player prefabs register themselves in a global static list on MasterClient.
AI wanders randomly until a closest player from the list is detected within detectionRadius, then chases.
Plays wandering & chasing sounds via AudioSources with no AudioClip assigned in inspector (clips assigned dynamically or by external script).
using System.Collections.Generic;
using UnityEngine;
public static class PlayerManager
{
public static List<Transform> allPlayers = new List<Transform>();
public static void RegisterPlayer(Transform playerTransform)
{
if (!allPlayers.Contains(playerTransform))
allPlayers.Add(playerTransform);
}
public static void UnregisterPlayer(Transform playerTransform)
{
if (allPlayers.Contains(playerTransform))
allPlayers.Remove(playerTransform);
}
}
Step 2: Create PlayerRegister.cs (attach to player prefab)
csharp
using Photon.Pun;
using UnityEngine;
public class PlayerRegister : MonoBehaviourPunCallbacks
{
void OnEnable()
{
// Only MasterClient keeps track to avoid duplicates/conflicts
if (PhotonNetwork.IsMasterClient)
{
PlayerManager.RegisterPlayer(transform);
}
}
void OnDisable()
{
if (PhotonNetwork.IsMasterClient)
{
PlayerManager.UnregisterPlayer(transform);
}
}
}
Step 3: Create SneakyAI.cs (attach to AI prefab)
csharp
Summary of What To Do:
Player prefab:
Attach PlayerRegister.cs.
Ensure the player GameObject has the tag Player.
Mark DontDestroyOnLoad as needed.
AI prefab:
Attach SneakyAI.cs.
Add NavMeshAgent component and set it up properly.
Add two empty AudioSources (no clips in inspector) and assign them to the wanderingAudioSource and chasingAudioSource fields on SneakyAI.
Add PhotonView component and configure it.
PlayerManager.cs should be in your project (does not need attaching).
NavMesh:
Bake your NavMesh in the scene.
Assign your AudioClips dynamically at runtime or via another script (since you requested no clips in AudioSource inspector).
Example for assigning AudioClip at runtime (optional):
If you want to assign the audio clips dynamically, here is a quick approach inside SneakyAI Start() before playing sounds:
csharp
void Start()
{
// Assuming you load/load your AudioClip e.g. from Resources or via a manager
wanderingAudioSource.clip = Resources.Load<AudioClip>("Sounds/WanderingSound");
chasingAudioSource.clip = Resources.Load<AudioClip>("Sounds/ChasingSound");
// rest of Start code...
}
If you want me to help with network syncing the AI's position and animation or sounds to all clients (for the full multiplayer feel), I can also provide that!
Let me know if you want it!
The error:
code
'PlayerManager' is missing the class attribute 'ExtensionOfNativeClass'!
sounds like Unity is interpreting your PlayerManager class as a MonoBehaviour derivative without a proper [ExtensionOfNativeClass] attribute, or you're trying to attach PlayerManager to a GameObject in the scene.
Why is this happening?
Your PlayerManager is a static plain C# class (not inheriting from MonoBehaviour), which means:
You should not attach PlayerManager to any GameObject in the scene.
It should be just a standard static class, placed anywhere in your Scripts folder.
It cannot have or require MonoBehaviour components or attributes.
How to fix this:
Make sure PlayerManager.cs is exactly like this:
csharp
using System.Collections.Generic;
using UnityEngine;
public static class PlayerManager
{
public static List<Transform> allPlayers = new List<Transform>();
public static void RegisterPlayer(Transform playerTransform)
{
if (!allPlayers.Contains(playerTransform))
allPlayers.Add(playerTransform);
}
public static void UnregisterPlayer(Transform playerTransform)
{
if (allPlayers.Contains(playerTransform))
allPlayers.Remove(playerTransform);
}
}
Do NOT attach the PlayerManager script/component to any GameObject in your scene.
If you had the PlayerManager script somewhere with : MonoBehaviour or tried to add it as a component, remove it.
If you want a MonoBehaviour alternative:
If you want to have a singleton PlayerManager MonoBehaviour instead (to track via Unity lifecycle events), you could do this as an alternative:
csharp
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager : MonoBehaviour
{
public static PlayerManager Instance;
public List<Transform> allPlayers = new List<Transform>();
private void Awake()
{
if (Instance != null && Instance != this)
Destroy(gameObject);
else
Instance = this;
DontDestroyOnLoad(gameObject);
}
public void RegisterPlayer(Transform playerTransform)
{
if (!allPlayers.Contains(playerTransform))
allPlayers.Add(playerTransform);
}
public void UnregisterPlayer(Transform playerTransform)
{
if (allPlayers.Contains(playerTransform))
allPlayers.Remove(playerTransform);
}
}
Then place thisPlayerManager script on a persistent GameObject in your starting scene.
Change the AI script to access PlayerManager.Instance.allPlayers instead of PlayerManager.allPlayers.
TL;DR
Your original PlayerManager class must be a static C# class, not MonoBehaviour, and not attached onto any GameObject.
Just keep it as a plain class to avoid this error.
If you want, I can provide the full revised scripts again with the singleton MonoBehaviour alternative to avoid confusion — just let me know!
Dataset releases
Not yet included in a published release.
using UnityEngine;
using UnityEngine.AI;
using Photon.Pun;
[RequireComponent(typeof(NavMeshAgent))]
[RequireComponent(typeof(PhotonView))]
public class SneakyAI : MonoBehaviourPunCallbacks
{
[Header("AI Settings")]
public float wanderRadius = 10f;
public float wanderInterval = 3f;
public float detectionRadius = 15f;
public float chaseSpeed = 4f;
public float wanderSpeed = 2f;
private NavMeshAgent agent;
private PhotonView pv;
private float wanderTimer;
private Vector3 wanderTarget;
private Transform chaseTarget;
private enum State { Wandering, Chasing }
private State currentState = State.Wandering;
[Header("Audio Sources (assign in inspector, no clips assigned!)")]
public AudioSource wanderingAudioSource;
public AudioSource chasingAudioSource;
void Start()
{
agent = GetComponent<NavMeshAgent>();
pv = GetComponent<PhotonView>();
// Validate audio sources
if (!wanderingAudioSource || !chasingAudioSource)
{
Debug.LogError("WanderingAudioSource and ChasingAudioSource must be assigned in inspector.");
enabled = false;
return;
}
wanderTimer = wanderInterval;
wanderingAudioSource.loop = true;
wanderingAudioSource.playOnAwake = false;
chasingAudioSource.loop = true;
chasingAudioSource.playOnAwake = false;
currentState = State.Wandering;
PlayWanderingSound();
agent.speed = wanderSpeed;
PickNewWanderTarget();
}
void Update()
{
// Run AI logic only on MasterClient
if (!PhotonNetwork.IsMasterClient) return;
switch (currentState)
{
case State.Wandering:
Wander();
LookForPlayer();
break;
case State.Chasing:
Chase();
CheckLostPlayer();
break;
}
}
void Wander()
{
wanderTimer -= Time.deltaTime;
if (wanderTimer <= 0f || HasReachedDestination())
{
PickNewWanderTarget();
wanderTimer = wanderInterval;
}
}
void PickNewWanderTarget()
{
Vector3 randomDirection = Random.insideUnitSphere * wanderRadius;
randomDirection += transform.position;
NavMeshHit navHit;
if (NavMesh.SamplePosition(randomDirection, out navHit, wanderRadius, NavMesh.AllAreas))
{
wanderTarget = navHit.position;
agent.SetDestination(wanderTarget);
}
agent.speed = wanderSpeed;
}
void LookForPlayer()
{
Transform closestPlayer = null;
float closestDistance = detectionRadius;
foreach (Transform playerTransform in PlayerManager.allPlayers)
{
if (playerTransform == null) continue;
float dist = Vector3.Distance(transform.position, playerTransform.position);
if (dist < closestDistance)
{
closestDistance = dist;
closestPlayer = playerTransform;
}
}
if (closestPlayer != null)
{
chaseTarget = closestPlayer;
ChangeState(State.Chasing);
}
}
void Chase()
{
if (chaseTarget == null)
{
ChangeState(State.Wandering);
return;
}
agent.SetDestination(chaseTarget.position);
agent.speed = chaseSpeed;
}
void CheckLostPlayer()
{
if (chaseTarget == null)
{
ChangeState(State.Wandering);
return;
}
float dist = Vector3.Distance(transform.position, chaseTarget.position);
if (dist > detectionRadius * 1.2f)
{
chaseTarget = null;
ChangeState(State.Wandering);
}
}
void ChangeState(State newState)
{
if (currentState == newState) return;
currentState = newState;
switch (newState)
{
case State.Wandering:
PlayWanderingSound();
agent.speed = wanderSpeed;
PickNewWanderTarget();
break;
case State.Chasing:
PlayChasingSound();
agent.speed = chaseSpeed;
break;
}
}
void PlayWanderingSound()
{
if (chasingAudioSource.isPlaying)
chasingAudioSource.Stop();
if (wanderingAudioSource.clip != null && !wanderingAudioSource.isPlaying)
wanderingAudioSource.Play();
}
void PlayChasingSound()
{
if (wanderingAudioSource.isPlaying)
wanderingAudioSource.Stop();
if (chasingAudioSource.clip != null && !chasingAudioSource.isPlaying)
chasingAudioSource.Play();
}
bool HasReachedDestination()
{
if (!agent.pathPending)
{
if (agent.remainingDistance <= agent.stoppingDistance)
{
if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
return true;
}
}
return false;
}
}