Particles to create star field in unity

Viewed 9607

I have a issue with a script. I am trying to create a star field randomly in a sphere for my unity scene. But I am new to unity and c# so I am a bit confused.

The stars have a fixed place so they should not move and so are created in Start(); and then are drawn in Update();

The problem is I get this error:

MissingComponentException: There is no 'ParticleSystem' attached to the "StarField" game object, but a script is trying to access it.
You probably need to add a ParticleSystem to the game object "StarField". Or your script needs to check if the component is attached before using it.
Stars.Update () (at Assets/Stars.cs:31)

If i add a particle system component manually it causes a load of big flashing orange spots, which i don't want, so i want to add the component in the script some how.

This is my script attached to an empty game object:

using UnityEngine;
using System.Collections;

public class Stars : MonoBehaviour {

    public int maxStars     = 1000;
    public int universeSize = 10;

    private ParticleSystem.Particle[] points;

    private void Create(){

        points = new ParticleSystem.Particle[maxStars];

        for (int i = 0; i < maxStars; i++) {
            points[i].position   = Random.insideUnitSphere * universeSize;
            points[i].startSize  = Random.Range (0.05f, 0.05f);
            points[i].startColor = new Color (1, 1, 1, 1);
        }

    }

    void Start() {

        Create ();
    }

    // Update is called once per frame
    void Update () {
        if (points != null) {

        GetComponent<ParticleSystem>().SetParticles (points, points.Length);

        }
    }
}

How can i set it to get a static star field, because adding a particle system component manually gives me these annoying orange particles and am wanting to do it purely via scripts.

1 Answers
Related