C# 粒子在统一中创建恒星场
我对脚本有问题。我试图在球体中为我的统一场景随机创建一个星场。但我对unity和c#还不熟悉,所以我有点困惑 星星有一个固定的位置,所以它们不应该移动,因此在Start()中创建;然后在Update()中绘制 问题是我得到了这个错误:C# 粒子在统一中创建恒星场,c#,unity5,particle-system,C#,Unity5,Particle System,我对脚本有问题。我试图在球体中为我的统一场景随机创建一个星场。但我对unity和c#还不熟悉,所以我有点困惑 星星有一个固定的位置,所以它们不应该移动,因此在Start()中创建;然后在Update()中绘制 问题是我得到了这个错误: MissingComponentException: There is no 'ParticleSystem' attached to the "StarField" game object, but a script is trying to access it
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);
}
}
}
使用UnityEngine;
使用系统集合;
公共级明星:单一行为{
公共整数maxStars=1000;
公共国际大学规模=10;
私有ParticleSystem.Particle[]点;
私有void Create(){
点=新粒子系统。粒子[maxStars];
对于(int i=0;i
我如何设置它来获得一个静态的星场,因为手动添加粒子系统组件会给我带来这些讨厌的橙色粒子,我想纯粹通过脚本来完成。如果手动添加粒子系统并更改设置,您将更容易在运行时或编辑器中看到任何有趣的形状 作为补充说明,不需要在“更新”中每帧设置粒子。即使您这样做了,调用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
}
}
使用UnityEngine;
公共类Starfield:单一行为
{
公共整数maxStars=1000;
公共国际大学规模=10;
私有ParticleSystem.Particle[]点;
私人分词系统;
私有void Create()
{
点=新粒子系统。粒子[maxStars];
对于(int i=0;i
这是一张带有粒子系统中使用的设置的星场截图。请注意,我关闭了循环
和唤醒播放
您是在运行游戏时获得橙色粒子,还是仅在Unity编辑器中获得橙色粒子?