I wrote a code that draws a line by mouse movement. I am searching for some way to give it pencil style and head and end of the line have thinner width. As we know the LineRenderer draws the line between points. How can I access first and last point elements to set the width of them and how can I do that?


Setting the width is a different operation from setting the points. You just need to use the SetWidth(a,b) method:

gameObject.GetComponent<LineRenderer>().SetWidth(2.0f, 1.5f);

However, the width is applied over the entire line. This likely won't work very well for your simulation of a pencil line. You'd probably want to create two LineRenderers. One for most of the line, which has a consistent width from start to finish, and a second for the last segment of the line, which will have its width taper off to something small.

| improve this answer | |

As of Unity 5.5 you can use an AnimationCurve.

To set only the start and end points you'd use something similar to:

gameObject.GetComponent<LineRenderer>().widthCurve = AnimationCurve.Linear(0, .5f, 1, .5f);

To set multiple points along the line to have a thinner start and end use something similar to:

AnimationCurve curve = new AnimationCurve();
curve.AddKey(0, 0);
curve.AddKey(.1f, .5f);
curve.AddKey(.9f, .5f);
curve.AddKey(1, 0);
gameObject.GetComponent<LineRenderer>().widthCurve = curve;

or this is another style of doing the same thing as above:

gameObject.GetComponent<LineRenderer>().widthCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(.1f, .5f), new Keyframe(.9f, .5f), new Keyframe(1, 0));
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.