- Home /
Put (Instantiate) Gameobject along or accross a path Unity
I'm a beginner on Unity and I want to create a personal project, alone. I have two Gameobjects on the Scene, I used LineRenderer and NavMesh agent on Unity to draw a path between two gameobjects, So far, everything's good, Unity draw path between two Gameobjects.
Void Update (){
OnDrawGiz(GameObject.Find("Destination"));
}
void OnDrawGiz(GameObject obj)
{
Transform target = obj.GetComponent<Transform> ();
NavMeshAgent nav;
LineRenderer line;
nav= this.GetComponent<NavMeshAgent>();
if( nav == null || nav.path == null )
return;
line = this.GetComponent<LineRenderer>();
line.material = new Material( Shader.Find( "Sprites/Default" ) ) { color
= Color.yellow };
line.startColor=Color.yellow;
line.endColor = Color.green;
nav.SetDestination (target.position);
nav.isStopped=true;
var path = nav.path;
if (path.corners.Length < 2)
return ;
line.positionCount=path.corners.Length ;
//Draw the line
for( int i = 0; i < path.corners.Length; i++ )
{
line.SetPosition( i, path.corners[i] );
}
}
Now my question is how can I put and duplicate a Gameobject for example a cube along or across this path please?! i want to achieve like this][2]
[2]: /storage/temp/95876-capture-decran-want.png
Answer by Dave-Carlile · Jun 13, 2017 at 05:50 PM
You can use the Vector3.Lerp function to find a point on a line in between any two vectors.
For example, given vectors a and b, you can find the vector directly in the middle like this:
Vector3 middle = Vector3.Lerp(a, b, 0.5f);
You can think of the t
parameter as a percentage between the two vectors. 0.5 is 50%, 0.25 would be 25%, and so on. If you want to add multiple objects you can use a loop variable to modify t
. For example:
for (int i = 0; i < 4; i++)
{
Vector3 position = Vector3.Lerp(a, b, i * 0.25f);
// TODO : create object at position
}