Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the positions of LineRenderer

Tags:

c#

unity3d

I wonder if there is a way to get the positions of nodes in a line renderer. In the project I'm working on I have a PseudoLine game object on which I have a line renderer. When I draw a line, I clone PseudoLine to create a new line. Using simply:

Instantiate(gameObject);

What I want to do is create new gameobjects with a prefab, which also has a line renderer on it. I want to copy the positions of PseudoLine to my new game object's line renderer. Something like this:

GameObject tempLine = Instantiate(line);
tempLine.GetComponent<LineRenderer>().SetPositions(transform.gameObject.GetComponent<LineRenderer>().Positions);

I checked the documentation and couldn't find any helpful built-in functions. How can I resolve this problem?

like image 689
Rookie Avatar asked Mar 09 '23 17:03

Rookie


1 Answers

You can use the LineRenderer.GetPositions and the LineRenderer.GetPosition functions to get the position of the LineRenderer.

It's recommended to use the LineRenderer.GetPositions function in this case since you are making a whole copy of the postions and LineRenderer.GetPositions will be fast for this.

To do this you need to create new Vector3 array and the length of this array should be the LineRenderer.numPositions value of the old LineRenderer you want to duplicate. In new version of Unity(5.6), this variable has been renamed to LineRenderer.positionCount.


GameObject oldLine = gameObject;
GameObject newLine = Instantiate(oldLine);

LineRenderer oldLineComponent = oldLine.GetComponent<LineRenderer>();

//Get old Position Length
Vector3[] newPos = new Vector3[oldLineComponent.positionCount];
//Get old Positions
oldLineComponent.GetPositions(newPos);

//Copy Old postion to the new LineRenderer
newLine.GetComponent<LineRenderer>().SetPositions(newPos);
like image 125
Programmer Avatar answered Mar 19 '23 13:03

Programmer