Skip to content

Instantly share code, notes, and snippets.

@shalperin
Created August 9, 2025 13:36
Show Gist options
  • Save shalperin/8e9fc28475f7303f967ea4160cd137af to your computer and use it in GitHub Desktop.
Save shalperin/8e9fc28475f7303f967ea4160cd137af to your computer and use it in GitHub Desktop.
Unity Spline Basics (Move a GameObject. along the length of a spline)
// Gist attached to YouTube video, please do not delete. See my YT channel, link in bio.
using UnityEngine;
using UnityEngine.Splines;
using Unity.Mathematics;
// This is applied to a boxing target flying at the user in my example.
// The whole Spline functionality comes from Unity's Window->Package Manager, and is in the Unity
// Registry.
public class FollowSpline : MonoBehaviour
{
public SplineContainer spline;
private float speed = .3f;
private float t = 0f;
// Update is called once per frame
private void OnValidate()
{
if (spline == null)
{
Debug.LogError($"{name}: Spline reference is missing!", this);
}
}
void Update()
{
// Here I'm just preventing a pileup of targets that have
// flown past the user.
if (t >= 1)
{
Destroy(gameObject);
return;
}
// Evaluate(...) here is expecting a value from 0..1, to interpolate the position
// along the spline's length. (also try the prompt: Tell me about 'out' parameters in C#...)
t += speed * Time.deltaTime;
spline.Evaluate(0, t, out float3 pos, out _, out _);
// ... and then just write that interpolated position to this GameObject.
transform.position = pos;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment