2017-09-06 74 views
0

有人能帮我理解我做错了什么,我得到NullReferenceException: Object reference not set to an instance of an object错误?使用获取/设置粒子来实例化粒子系统

这是从旧的辅导采取了原本不实例化ParticleSystem,所以基础上,回答了类似的帖子,我已经修改了它的工作,但现在看来似乎仍然没有实例...

最初,它只在Update方法中使用了particleSystem.SetParticles(points, points.Length);,但这并不奏效,寻找答案让我找到了一个专门的帖子来解决这个问题,但是建议的解决方案仍然无法实现。

我在这里做错了什么?

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class Grapher1 : MonoBehaviour 
{ 
    public int _resolution = 10; 
    private ParticleSystem.Particle[] _points; 
    private ParticleSystem _particleSystem; 


    private void Start() 
    { 
     if (_resolution < 10 || _resolution > 100) 
     { 
      Debug.LogWarning("Grapher resolution out of bounds, resetting to minimum 10", this); 
      _resolution = 10; 
     } 

     _points = new ParticleSystem.Particle[_resolution]; 
     _particleSystem.Emit(_resolution); 
     _particleSystem.GetParticles(_points); 

     float increment = 1f/(_resolution - 1); 
     for (int i = 0; i < _resolution; i++) 
     { 
      float x = i * increment; 
      _points[i].position = new Vector3(x, 0f, 0f); 
      _points[i].color = new Color(x, 0f, 0f); 
      _points[i].size = 0.1f; 
     } 
    } 


    private void Update() 
    { 
     _particleSystem.SetParticles(_points, _points.Length); 
    } 
} 
+1

你在哪里分配一个有效的对象到'_particleSystem '? – UnholySheep

+1

双击编辑器中的错误,它会显示导致该错误的代码行。告诉我们这行代码的样子。 – Programmer

+0

@UnholySheep我创建一个私有实例,然后使用点运算符提供的公共方法。这不够吗? – Joshua

回答

2
作为

在评论中讨论:

private ParticleSystem _particleSystem; 

只声明了一个(参考)变量,它不创建实例。

使用ParticleSystem的优选方法是通过在Start()方法加入

_particleSystem = GetComponent<ParticleSystem>(); 

到它经由GetComponent附加到游戏对象,然后引用它,在这种情况下。

另一种选择是编程方式经由GameObject.AddComponent一个组件添加到游戏物体,然而,通常优选直接经由编辑器附接部件(如AddComponent增加运行时开销)