Unity Trail Renderer and Line Renderer: Trails, Lasers and Aim Lines

Illustration: a glowing sword swing trail and a laser beam line crossing

Sword swings, bullet streaks, dash afterimages, laser beams and “where will this grenade land” aim lines all come from two small components: the Trail Renderer and the Line Renderer. They are cheap, need no particle setup and look great with a good width curve and gradient. This guide covers the Unity Trail Renderer and Line Renderer in practice: what each is for, the settings that matter, and working scripts for a bullet trail, a laser and a trajectory preview.

Trail vs Line: Which One

  • Trail Renderer draws a ribbon behind a moving object automatically. You add it, move the object, and it records the path. Use it for bullets, swords, projectiles, comet tails and dash streaks.
  • Line Renderer draws a line through points you give it. It does not move on its own. Use it for lasers, ropes, aim lines, lightning and trajectory previews.

Both use the same material and width and gradient settings, so what you learn for one transfers to the other.

Trail Renderer Setup

Select a moving object, choose Add Component > Effects > Trail Renderer, and press Play. The important properties:

  • Time: how many seconds a trail point lives. A short value (0.1 to 0.3) gives a tight streak. A long value gives a lazy tail.
  • Min Vertex Distance: how far the object must move before a new point is added. Lower is smoother but costs more.
  • Autodestruct: destroys the GameObject when the trail has finished fading and the object stops moving. Handy for one-shot effects, dangerous for anything you want to keep.
  • Emitting: turn it on and off to start and stop the trail without destroying it.
  • Width: a curve across the trail length. Taper it to zero at the end for a clean fade.
  • Color: a gradient along the trail, with alpha.
  • Alignment: View faces the camera, which is what you want for most effects. Transform Z faces along the object’s local Z axis.

The same can be done in code, which is useful for enabling a dash trail only while dashing:

using UnityEngine;

[RequireComponent(typeof(TrailRenderer))]
public class DashTrail : MonoBehaviour
{
    TrailRenderer trail;

    void Awake()
    {
        trail = GetComponent<TrailRenderer>();
        trail.emitting = false;
    }

    public void StartDash()
    {
        trail.Clear();          // remove old points so it doesn't stretch from the last position
        trail.emitting = true;
    }

    public void EndDash() => trail.emitting = false;
}

Clear() matters. If you teleport an object, the trail draws a long line from the old position to the new one. Call Clear after teleporting, or after re-using a pooled bullet. Connect this to your dash code, such as the one in the dash ability guide.

Width Curve and Gradient

A trail that is the same width and colour along its length looks like a flat ribbon. Two changes make it look professional: taper the width, and fade the alpha.

void ConfigureTrail(TrailRenderer trail)
{
    // Width: full at the head, zero at the tail
    var width = new AnimationCurve(
        new Keyframe(0f, 1f),
        new Keyframe(1f, 0f));
    trail.widthCurve = width;
    trail.widthMultiplier = 0.3f;

    // Colour: bright orange fading to transparent red
    var gradient = new Gradient();
    gradient.SetKeys(
        new[]
        {
            new GradientColorKey(new Color(1f, 0.8f, 0.2f), 0f),
            new GradientColorKey(new Color(1f, 0.2f, 0f), 1f)
        },
        new[]
        {
            new GradientAlphaKey(1f, 0f),
            new GradientAlphaKey(0f, 1f)
        });
    trail.colorGradient = gradient;

    trail.time = 0.25f;
    trail.minVertexDistance = 0.05f;
}

In the Inspector, the same thing is done by clicking the curve and gradient fields. In the Gradient editor, the top markers control alpha and the bottom markers control colour. Pooled objects should call Clear() when re-spawned. Trails pair well with the effects in the game feel and juice guide, and with projectiles from the shooting projectiles guide. Add a Trail Renderer to the bullet prefab and you are done.

Line Renderer Basics

Add one with GameObject > Effects > Line, or Add Component > Effects > Line Renderer. You give it a list of points and it draws segments between them.

  • Positions: the points. In code, set positionCount and then call SetPosition(index, point), or pass an array to SetPositions.
  • Use World Space: when on, positions are world coordinates and the line does not move with its object. When off, they are relative to the object. Lasers that follow a gun are easier in local space. Trajectory lines are easier in world space.
  • Loop: joins the last point back to the first. Good for circles and selection rings.
  • Corner Vertices and End Cap Vertices: add smoothing to sharp bends and round ends.
  • Texture Mode: Stretch stretches the texture across the whole line. Tile repeats it, which suits dashed lines and ropes.

A Laser Beam That Stops at Walls

A laser is two points: the muzzle and wherever a raycast hits. This script updates the line every frame:

using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class LaserBeam : MonoBehaviour
{
    [SerializeField] float maxDistance = 50f;
    [SerializeField] LayerMask hitMask = ~0;

    LineRenderer line;

    void Awake()
    {
        line = GetComponent<LineRenderer>();
        line.positionCount = 2;
        line.useWorldSpace = true;
    }

    void Update()
    {
        Vector3 start = transform.position;
        Vector3 end = start + transform.forward * maxDistance;

        if (Physics.Raycast(start, transform.forward, out RaycastHit hit, maxDistance, hitMask))
            end = hit.point;

        line.SetPosition(0, start);
        line.SetPosition(1, end);
    }
}

Put the script on an empty object at the gun’s muzzle, pointing along its forward axis. You can spawn a spark at hit.point for extra polish. For instant-hit guns, a quick flash of a Line Renderer between the muzzle and impact makes a good tracer, as used in the hitscan gun guide. Enable the renderer for a few frames on shot and turn it off, instead of leaving it on.

A Trajectory Preview

For grenades and thrown items, draw the arc before the throw. You can compute positions with the projectile motion formula, no simulation needed: position = start + velocity x time + 0.5 x gravity x time squared.

using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class TrajectoryPreview : MonoBehaviour
{
    [SerializeField] int steps = 30;
    [SerializeField] float timeStep = 0.1f;
    [SerializeField] LayerMask hitMask = ~0;

    LineRenderer line;

    void Awake()
    {
        line = GetComponent<LineRenderer>();
        line.useWorldSpace = true;
    }

    public void Show(Vector3 startPos, Vector3 startVelocity)
    {
        var points = new Vector3[steps];
        int count = 0;
        Vector3 previous = startPos;

        for (int i = 0; i < steps; i++)
        {
            float t = i * timeStep;
            Vector3 p = startPos + startVelocity * t + 0.5f * Physics.gravity * t * t;

            // stop the line where it hits something
            if (i > 0 && Physics.Linecast(previous, p, out RaycastHit hit, hitMask))
            {
                points[count++] = hit.point;
                break;
            }

            points[count++] = p;
            previous = p;
        }

        line.positionCount = count;
        line.SetPositions(points); // uses the first positionCount entries
    }

    public void Hide() => line.positionCount = 0;
}

Call Show every frame while the player aims, using the same start position and velocity that the throw will use, and Hide on release. The two must match: if the real grenade is a Rigidbody launched with an Impulse, divide the impulse by mass to get the starting velocity. Allocating an array each frame creates garbage, so in a shipped game keep the array as a field and reuse it. See the garbage collection guide for why this matters. The same trick works for a bow and for 2D games using Physics2D.gravity.

Materials and URP

New trails and lines may render pink or white depending on your pipeline and default material. Assign a material explicitly:

  • Create a Material with an Unlit shader (in URP, the Universal Render Pipeline/Unlit shader or a Particles Unlit shader). Set Surface Type to Transparent if you want alpha fade, and Blending Mode to Additive for glowing effects.
  • For a soft streak, use a texture that fades at the edges. Set Texture Mode to Stretch on the renderer.
  • For glow, use an HDR colour on the material and enable Bloom in your post-processing Volume.

🔧 Effects packs

Trail textures, shaders and VFX packs save time. See our recommended Asset Store tools.

Troubleshooting

The trail or line is pink

The material’s shader is not compatible with your render pipeline. Use a URP Unlit or Particles shader, not a Built-in one.

The trail draws a line from where the object was to where it is now

The object was teleported or re-used from a pool. Call trail.Clear() after moving it.

The trail is invisible

Check the width multiplier is not zero, the gradient alpha is not zero, the material is assigned and the object is actually moving. A trail on a static object has nothing to draw.

The trail looks jagged on fast curves

Reduce Min Vertex Distance, increase Corner Vertices, or move the object in FixedUpdate and Update consistently. Moving a Rigidbody trail object without Interpolate also gives choppy results.

The Line Renderer follows the object when I do not want it to

Use World Space is off. Tick it so the points are world coordinates.

Trail disappears when the object is destroyed

The trail is a child of the object. Detach it, or let Autodestruct and a delayed Destroy on a separate trail object finish the fade.

FAQ

Trail Renderer or Particle System trail?

The Trail Renderer is simpler and good for single objects. Particle systems with the Trails module suit many particles at once.

Are Line Renderers expensive?

No, a few are cheap. Hundreds of high-vertex lines updated every frame add up, so cap the number of points.

How do I make a sword swing trail?

Put a Trail Renderer on a child at the blade tip, set a short Time, and enable Emitting only during the swing animation.

Can I animate a Line Renderer between two moving objects?

Yes. Update the two positions each frame in LateUpdate, after both objects have moved.

How do I make lightning?

Add several points between start and end and offset each one randomly sideways, regenerating a few times per second.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *