粒子系统无法在Play()上运行

时间:2017-08-02 22:46:10

标签: c# unity3d

我有一个粒子效果,我想触发,然后停止。我确信这是一个很容易解决的问题。

粒子可以实例化和播放,但这显然会留下开销和粒子,当它们不需要时,它们在层次结构中是活跃的。

public void EmitFX(ParticleSystem particle)
{
   Instantiate(particle, particlePos, Qauternion.identity)
}

我想在ParticleSystem中使用方法,但遇到了一些问题。我一直在使用手册,但仍然遇到了障碍。我已经上下搜索了这个问题,基于其他问题,我将代码更改为以下内容。它仍然不起作用,现在是一个基于其他人认为有用的黑客的怪物:/

public void EmitFX(ParticleSystem particle)
    {
        particle = particle.GetComponent<ParticleSystem>();
        particle.transform.position = ballPos;

        var em = particle.emission;
        em.enabled = true;       

        particle.Play();
    }

以下是Inspector中粒子的s / c。

enter image description here

2 个答案:

答案 0 :(得分:3)

首先,不确定particle = particle.GetComponent<ParticleSystem>();行应该做什么? particle变量是 ParticleSystem 提供给您的EmitFX()方法,因此无需为此调用。

我的猜测是你的脚本中有一些引用问题(一些变量指的是你的预制件,然后你实例化的内容会覆盖这个引用,......)所以我写了一个&#34; clean&#34;您的代码版本(通过合并两个脚本):

#region Attributes
[SerializeField]
private ParticleSystem particle;

private ParticleSystem generatedParticle;
#endregion

#region MonoBehaviour
protected void Start()
{
    generatedParticle = null;
}

protected void Update()
{
    if(Input.GetKeyDown(KeyCode.Space))
    {
        EmitFX(particle);
    }
}
#endregion

public void EmitFX(ParticleSystem a_Particle)
{
    if(generatedParticle == null)
    {
        generatedParticle = Instantiate(particle, particlePos, Qauternion.identity);
    }

    generatedParticle.transform.position = ballPos;       
    generatedParticle.Play();

    // You can set a fixed duration here if your particle system is looping
    // (I assumed it was not so I used the duration of the particle system to detect the end of it)
    StartCoroutine(StopFXAfterDelay(generatedParticle.main.duration));
}

private IEnumerator StopFXAfterDelay(float a_Delay)
{
    yield return new WaitForSeconds(a_Delay);
    generatedParticle.Stop();
}

它的作用是将实例化的粒子存储在变量中,以便以后可以访问它并记住它已经生成。我还添加了一个协程来在效果结束时停用它。

希望这有帮助,

答案 1 :(得分:0)

我知道这是一个古老的问题,但是我将在这里介绍对我有用的东西,因为该问题在Unity的更高版本中仍然存在。

不仅要调用:>,而且要像下面的代码一样先停止粒子系统。

particle.Play()

“粒子”是“ ParticleSystem”类型的组件。

相关问题