C# Script for Creating a Cursor Trail Effect in Unity

Below is a script that generates a trail that follows the mouse cursor in Unity.

Sharp Coder Video Player

  • Create a new script, name it SC_CursorTrail then paste the code below inside it:


using UnityEngine;

public class SC_CursorTrail : MonoBehaviour
    public Color trailColor = new Color(1, 0, 0.38f);
    public float distanceFromCamera = 5;
    public float startWidth = 0.1f;
    public float endWidth = 0f;
    public float trailTime = 0.24f;

    Transform trailTransform;
    Camera thisCamera;

    // Start is called before the first frame update
    void Start()
        thisCamera = GetComponent<Camera>();

        GameObject trailObj = new GameObject("Mouse Trail");
        trailTransform = trailObj.transform;
        TrailRenderer trail = trailObj.AddComponent<TrailRenderer>();
        trail.time = -1f;
        trail.time = trailTime;
        trail.startWidth = startWidth;
        trail.endWidth = endWidth;
        trail.numCapVertices = 2;
        trail.sharedMaterial = new Material(Shader.Find("Unlit/Color"));
        trail.sharedMaterial.color = trailColor;

    // Update is called once per frame
    void Update()

    void MoveTrailToCursor(Vector3 screenPosition)
        trailTransform.position = thisCamera.ScreenToWorldPoint(new Vector3(screenPosition.x, screenPosition.y, distanceFromCamera));
  • Attach SC_CursorTrail to Main Camera

Press Play and observe the trail that follows the cursor.

Suggested Articles
Script for Creating a Light Switch in Unity
FPC Swimmer - A Comprehensive Unity Asset for Immersive Water Environments
Mouse Look Script for Unity
Raycast and Projectile-based Gun Shooting Script for Unity
2D Melee Attack Tutorial for Unity
Slow Motion Effect in Unity
How to Set Up Joystick Controller for Movement in Unity