- Home /
NavMeshAgent/Timer Countdown not working,Nav MeshAgent/ Timer stops working
I want to make the GameObject attached to this script walk randomly and when it spots another GameObject it should walk towards it. That is working but after some time ( when I relaunch it, the time is different) it stops to count down. Has anybody an Idea how to fix this?
[code=CSharp]using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI;
public class slaveNavi : MonoBehaviour { NavMeshAgent agent; [SerializeField] float range = 10f; Vector3 enemyPos; Vector3 oldPos;
public float wanderRadius = 10f;
public float wanderTimer = 3f;
private Transform target;
private float timer;
bool spotted = false;
// Start is called before the first frame update
void Start()
{
agent = GetComponent<NavMeshAgent>();
oldPos = gameObject.transform.position;
timer = wanderTimer;
}
void Update()
{
timer -= Time.deltaTime;
}
// Update is called once per frame
void FixedUpdate()
{
spotEnemy();
}
void spotEnemy()
{
RaycastHit hit;
Debug.DrawRay(transform.position + new Vector3(0, 0.5f, 0.5f), transform.forward.normalized * 10, Color.red, 2);
if (Physics.Raycast(transform.position + new Vector3(0,0.5f,0.5f), transform.forward.normalized, out hit, range))
{
if(hit.transform.gameObject.tag == "Slave")
{
enemyPos = hit.transform.position;
agent.SetDestination(enemyPos);
}
}
else
{
Debug.Log(timer);
if (timer <= 0f)
{
Vector3 newPos = RandomNavSphere(transform.position, wanderRadius, -1);
agent.SetDestination(newPos);
timer = wanderTimer;
Debug.Log("Sucess");
agent.enabled = true;
}
}
}
public static Vector3 RandomNavSphere(Vector3 origin, float dist, int layermask)
{
Vector3 randDirection = Random.insideUnitSphere * dist;
randDirection += origin;
NavMeshHit navHit;
NavMesh.SamplePosition(randDirection, out navHit, dist, layermask);
return navHit.position;
}
} [/code]
Your answer
Follow this Question
Related Questions
Making an FPS arcade game. 0 Answers
Need help detecting barriers for my game 0 Answers
How to get a velocity unit vector from a NavMeshAgent? 1 Answer
Navmesh agent forward movement 1 Answer
Multiple Cars not working 1 Answer