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(); 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); } }