使用粒子在Unity中创建星空场景

7

我有一个脚本的问题。我正在尝试在Unity场景中为球体随机创建星空。但我对Unity和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)

如果我手动添加粒子系统组件,它会导致大量闪烁的橙色斑点,这不是我想要的,因此我想以某种方式在脚本中添加该组件。
这是我的脚本附加到一个空游戏对象上:
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);

        }
    }
}

我该如何设置静态星空呢?手动添加粒子系统组件会给我带来这些令人讨厌的橙色粒子,我想通过脚本纯粹地实现它。


你在运行游戏时还是只在Unity编辑器中看到了橙色的粒子? - James Bateson
1个回答

11

如果您手动添加粒子系统并更改设置,使在运行时或编辑器中不会看到任何奇怪的形状,那么这将更容易些。

顺便提一下,在Update中无需每帧设置粒子。即使您这样做了,调用GetComponent也很耗费资源,因此您应该在Start()方法中将ParticleSystem保存为类的字段。

这是一些为我工作的修改后的代码:

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

这是使用粒子系统设置的星空截图。请注意,我关闭了循环唤醒时播放

设置


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接