- Home /
How do I change Nav Mesh Agent Speed with c# Script ?
I have several "Nav Mesh Agents" in my program and I want to assign certain variables randomly.
In the Inspector/NavMeshAgent, I know how to set my agents Speed and Acceleration manually. And I know how to create random numbers using Random.Range(min, max)...no problem there.
I simply cannot find the unity/C# syntax to assign random values to those attributes.
Answer by Dibbie · Nov 21, 2016 at 10:08 AM
I would take a look at the documentation for NavMeshAgent, it will cover all the functions you can use by script.
So you can set the speed at random, with an idea like GetComponent<NavMeshAgent>().speed = Random.Range(0.1f, 10.0f);
as an example.
Thank you kindly. I think I tried about everything I could think of but, as it turns out, I didn't try what you have posted there. It Works Great!!!
I really appreciate you taking the time to help me.
I read the documentation but I will read it again. I'm not quite experienced enough (yet) to always fully understand what I read the first time.
Again, thanks.
Answer by bojantube · Mar 01, 2020 at 06:31 AM
@Dibbie how do i change values to stop distance? this.GetComponent().stoppingDistance = 0.001f; how?
Hi @bojantube
There are a few different things you can do:
You can change it in the Inspector, by opening the NavMeshAgent component, and lowering the stopping distance to the $$anonymous$$imum it will go which is 0.
You can change it in your script to 0 for Mathf.Epsilon. (Mathf.Epsilon is a ridiculously low float number, the smallest number you can do. i.e. 0.000....1)
You can cache it is the awake function. The reason why you want to cache it in Awake is because Awake() gets called before Start() does, and it will stop the having to use :
_exampleObject.GetComponent<ExampleComponent>();
When GetComponent is called way too often, it can create lag and actually cause the game to run a lot slower than cacheing the objects in Awake()
Cache other things, like object references in there as well:
( Using 'this.blahblah' in this matter is considered "Redundant". I would use 'this.blahblah' only if this script is on multiple objects)
private void Awake()
{
_exampleAgent = this.GetComponent<NavMeshAgent>();
_examplePlayerObject = GameObject.Find("Player");
}
private void ExampleMethod()
{
_exampleAgent.stoppingDistance = Mathf.Epsilon;
}
I can't get the code section to work, sorry about that lol
Your answer
Follow this Question
Related Questions
first random positon is always the same 2 Answers
Can you randomise a Navmesh agents rotation 1 Answer
Add randomness to Navmeshagent 0 Answers
[SOLVED] NavMeshAgent Create Imperfect Paths? [SOLVED] 1 Answer
AI pathfinding waypoints 1 Answer