- Home /
Linerenderer Inconsistency
Hi, I am trying to draw a line between my nav mesh agent and it's destination.
https://gyazo.com/0ac93ab1199111d878ee1c234478650c
This is how it works so far. It works, but sometimes the line doesn't appear, or it appears on the next click (one click to late). It usually doesn't appear if I click too far away.
I want to click somewhere and then show the path already, and it does this sometimes. I am not sure what I have to do to increase the performance of this linerenderer.
Linerenderer script.
using UnityEngine;
using System.Collections;
public class PathLine : MonoBehaviour {
LineRenderer Line;
NavMeshPath Path;
public Material mat;
void Start () {
Line = GetComponent<LineRenderer>();
}
public void Pathlinetex(NavMeshPath Path) {
Line.material = mat;
//new Material(Shader.Find("Sprites/Default")) { color = Color.red };
Line.SetWidth(0.20f, 0.20f);
//Line.SetColors(Color.red, Color.red);
Line.SetVertexCount(Path.corners.Length);
for (int i = 0; i < Path.corners.Length; i++)
{
Line.SetPosition(i, Path.corners[i]);
}
}
}
ClickToMove Script.
using UnityEngine;
using System.Collections;
public class ClickMove : MonoBehaviour {
NavMeshAgent navAgent;
NavMeshPath ppath;
static Animator aanimation;
void Start ()
{
navAgent = GetComponent<NavMeshAgent>();
aanimation = GetComponent<Animator>();
}
void Update()
{
Animating();
RaycastHit hit; //Hold information where raycast hits terrain
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // The ray goes from camera to mouse
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(ray, out hit, 100))
{
navAgent.SetDestination(hit.point);
ppath = navAgent.path;
GetComponent<PathLine>().Pathlinetex(ppath);
}
}
}
void Animating()
{
if (navAgent.velocity.magnitude > 1f)
{
aanimation.SetBool("isSneaking", true);
}
else {
aanimation.SetBool("isSneaking", false);
}
}
}
Answer by Bunny83 · Apr 13, 2016 at 12:05 AM
Just read the docs carefully:
Note that the path may not become available until after a few frames later. While the path is being computed, pathPending will be true. If a valid path becomes available then the agent will resume movement.
The pathfinding is done asynchonously in the background so you don't get live feedback. If you need to know the path immediately you might want to look at NavMeshAgent.CalculatePath. However it's probably better to check NavMeshAgent.pathPending in Update or a coroutine and do your linerenderer settings when the path has been calculated. A Coroutine will most likely be the best solution.
IEnumerator SetTarget(Vector3 pos)
{
navAgent.SetDestination(hit.point);
while (navAgent.pathPending)
yield return null;
ppath = navAgent.path;
GetComponent<PathLine>().Pathlinetex(ppath);
}
And in your click method simply do:
if (Physics.Raycast(ray, out hit, 100))
{
StartCoroutine(SetTarget(hit.point));
}