粒子在团结中创造星场

WDU*_*DUK 5 c# particle-system unity5

我的脚本有问题.我试图在一个球体中随机创建一个星场,用于我的统一场景.但我对团结和c#是新手,所以我有点困惑.

星星有一个固定的位置,所以它们不应该移动,因此在Start()中创建; 然后在Update()中绘制;

问题是我收到此错误:

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)
Run Code Online (Sandbox Code Playgroud)

如果我手动添加一个粒子系统组件,它会导致一大堆闪烁的橙色斑点,这是我不想要的,所以我想在脚本中添加一些组件.

这是我附加到空游戏对象的脚本:

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

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如何设置它以获得静态星形区域,因为手动添加粒子系统组件会给我带来这些恼人的橙色粒子,并且我希望纯粹通过脚本来完成它.

Jam*_*son 8

如果手动添加粒子系统并更改设置,以便在运行时或编辑器中看不到任何有趣的形状,将会更容易.

作为旁注,您不需要在Update中每帧设置粒子.即使你这样做,调用GetComponent也很昂贵,所以你应该把它ParticleSystem作为类的一个字段保存在Start()方法中.

这是一些适合我的修改后的代码:

using UnityEngine;

public class Starfield : MonoBehaviour 
{

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

    private ParticleSystem.Particle[] points;

    private ParticleSystem particleSystem;

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

        particleSystem = gameObject.GetComponent<ParticleSystem>();

        particleSystem.SetParticles(points, points.Length);
    }

    void Start()
    {
        Create();
    }

    void Update()
    {
        //You can access the particleSystem here if you wish
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是星形图的截图,其中包含粒子系统中使用的设置.请注意,我关掉loopingplay on awake.

设置