- Home /
problem with ai
So I have a WIP script that is a simple AI that follows the player when sees it, and then when she doesn't chase you she will walk around randomly. The problem is that I created public transform[] aiWanderPoints and now I don't know how to choose a random element. Here's my script:
using UnityEngine; using UnityEngine.AI;
public class AI : MonoBehaviour { public Transform Player; private NavMeshAgent agent; public Transform[] aiWanderPoints;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
agent.SetDestination(Player.position);
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
agent.SetDestination(aiWanderPoints[].position);
}
}
}
Answer by Fariborzzn · May 03, 2021 at 01:25 AM
Hey @MaxPlayer2011 as I can see you have a array of points that AI can reach out when player is not in trigger zone . what you need is getting an random element from this array . so change your OnTriggerExit to this :
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
agent.SetDestination(aiWanderPoints[Random.Range(0, aiWanderPoints.Count)].position);
}
}
Random.Range mthod will generate a random number for you .. let me know if your problem was solved or you have more question Best regards Fariborz
I'm getting an error:
AI.cs(27,80): error CS1061: 'Transform[]' does not contain a definition for 'Count' and no accessible extension method 'Count' accepting a first argument of type 'Transform[]' could be found (are you missing a using directive or an assembly reference?)
Yes, there is no method 'Count' for an array :D Use 'Length' instead.
Here @Fariborzzn 's code changed for using an array instead of a List:
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
agent.SetDestination(aiWanderPoints[Random.Range(0, aiWanderPoints.Length)].position);
}
}
That should fix your error :P
:D Remember array have length not count Remember array have length not count Remember array have length not count Remember array have length not count