Change NavMeshAgent Speed With Script?
I've been trying to access the speed float with my other script. I can't change the speed with the other script but I can with the script it is in. This is my enemy movement script:
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.AI;
 
 public class EnemyMove : MonoBehaviour
 {
     public Transform player;
     NavMeshAgent agent;
 
     public static float speed = 1.0f;
 
     // Start is called before the first frame update
     void Start()
     {
         agent = GetComponent<NavMeshAgent>();
         agent.speed = speed;
     }
 
     // Update is called once per frame
     void Update()
     {
         //Follow the player
         agent.destination = player.position;
     }
 }
 
               This is the code I used to reference. I have a collision and whenever it collides, I want the speed to go up. I used this:
 public static int left = 4;
 
 EnemyMove.speed += 1.5f;
 
               Please help I've searched everywhere couldn't find an answer. Thanks
Answer by Ascaria · Jan 09, 2021 at 10:51 PM
Simplest: move this to update loop:
 agent.speed = speed;
 
               But be aware that every instance of enemy will be influenced.
Better: theoretically, in collision method, you can search for EnemyMove component, if found, you can then search again for NavMeshAgent and change its speed directly
     private void OnCollisionEnter(Collision collision) {
         EnemyMove enemyMove = collision.gameObject.GetComponentInChildren<EnemyMove>();
         if(enemyMove != null) {
             NavMeshAgent agent = GetComponent<NavMeshAgent>();
             agent.speed = 1234f;
         }
     }
 
               Note: if EnemyMove is attached to collider's parent, use GetComponentInParent
Your answer
 
             Follow this Question
Related Questions
Object reference not set to an instance of an Object? 0 Answers
Help with good coding practices and player Nav Mesh Agent Jumps. Thanks. 1 Answer
Creating prefab through Zenject Factory makes navMeshAgent act strange 0 Answers
how can I implement navmesh in this script? 0 Answers
NavMeshAgent dont find the right way on runtime build NavMesh 0 Answers