Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Forked from silverua/StarField.cs
Created May 11, 2025 11:36
Show Gist options
  • Save unitycoder/954e2edf5fcdc412b70a3a9b5f99c1ac to your computer and use it in GitHub Desktop.
Save unitycoder/954e2edf5fcdc412b70a3a9b5f99c1ac to your computer and use it in GitHub Desktop.
Script for StarField background in Unity from this tutorial: https://www.youtube.com/watch?v=yu23OAd_Wrw&list=LL
using UnityEngine;
using Random = UnityEngine.Random;
public class StarField : MonoBehaviour
{
private Transform thisTransform;
private ParticleSystem.Particle[] points;
public int starsMax = 100;
public float starSize = 1f;
public float starDistance = 10f;
public float starClipDistance = 1f;
// do not touch, internal math stuff
private float starDistanceSqr;
private float starClipDistanceSqr;
private ParticleSystem ps;
// Use this for initialization
private void Start()
{
thisTransform = transform; // caching the transform
starClipDistanceSqr = starClipDistance * starClipDistance;
starDistanceSqr = starDistance * starDistance;
ps = GetComponent<ParticleSystem>();
var main = ps.main;
main.simulationSpace = ParticleSystemSimulationSpace.World;
}
private void CreateStars()
{
points = new ParticleSystem.Particle[starsMax];
for (int i = 0; i < starsMax; i++)
{
points[i].position = Random.insideUnitSphere.normalized * starDistance + thisTransform.position;
points[i].color = new Color(1, 1, 1, 1);
points[i].size = starSize;
}
}
// Update is called once per frame
private void Update()
{
if (points == null)
{
CreateStars();
}
for (int i = 0; i < starsMax; i++)
{
if ((points[i].position - thisTransform.position).sqrMagnitude > starDistanceSqr)
{
points[i].position = Random.insideUnitSphere.normalized * starDistance + thisTransform.position;
}
if ((points[i].position - thisTransform.position).sqrMagnitude <= starDistanceSqr)
{
float percent = (points[i].position - thisTransform.position).sqrMagnitude / starClipDistanceSqr;
points[i].color = new Color(1, 1, 1, percent);
points[i].size = percent * starSize;
}
}
ps.SetParticles(points, points.Length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment