I have been attempting to add a "range" of sorts to my enemy movement (too many move toward the player at once) and I have seen one solution but I am uncertain how to implement it as it doesn't really detect that I'm using the dis and distval values.
I am not trying to add any movement or route for them to follow. Just a wide (but not too wide) activation sphere of sorts. (also note that I am new, and I know it's probably a stupid question to ask, but I still don't know the answer to it and can't find it ((or at the very least understand it))).
here is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Follow : MonoBehaviour
{
public NavMeshAgent enemy;
public Transform Player;
// Update is called once per frame
void Update()
{
var distVal = 5.0f;
var dis = Vector3.Distance(enemy.position, Player.position);
if (dis <= disVal)
{
enemy.SetDestination(Player.position);
}
}
}
CodePudding user response:
If you set a NavMeshAgent's destination to be its own position it will stop moving.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Follow : MonoBehaviour
{
public NavMeshAgent enemy;
public Transform Player;
// Update is called once per frame
void Update()
{
float distVal = 5.0f;
float dist = Vector3.Distance(enemy.transform.position, Player.position);
if (dist <= distVal)
{
enemy.SetDestination(Player.position);
}
else
{
enemy.SetDestination(enemy.transform.position);
}
}
}
This should do what you want. But I should point out you were never using your distVal variable, and that enemy.position should have been enemy.transform.position.