以编程方式启动时破坏粒子系统



我有一个玩家和一个敌人的游戏。

我还有一个粒子系统,用于玩家死亡时,比如爆炸。 我已经将这个粒子系统制作为预制件,因此我可以在每个关卡中多次使用它,因为有人可能会死很多。

所以在我的敌人.cs脚本中,附在我的敌人身上,我有:

public GameObject deathParticle;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.name == "Player" && !player.dead){
player.dead = true;
Instantiate(deathParticle, player.transform.position, player.transform.rotation);
player.animator.SetTrigger("Death");
}
}

所以当玩家被敌人杀死时,它会播放我的粒子系统。现在在我的播放器脚本上,我有这个。此特定功能在死亡动画之后播放:

public void RespawnPlayer()
{
Rigidbody2D playerBody = GetComponent<Rigidbody2D>();
playerBody.transform.position = spawnLocation.transform.position;
dead = false;
animator.Play("Idle");
Enemy enemy = FindObjectOfType<Enemy>();
Destroy(enemy.deathParticle);
}

这会像往常一样重生玩家,但在我的项目中,每次我死后,我都有一个我不想要的死亡(克隆(对象。最后 2 行旨在删除它,但它没有。

我也试过这个不起作用:

Enemy enemy = FindObjectOfType<Enemy>();
ParticleSystem deathParticles = enemy.GetComponent<ParticleSystem>();
Destroy(deathParticles);

无需InstantiateDestroy死亡粒子,这将产生大量开销,您可以在希望它启动和停止它时简单地重播它,当您不需要它时

ParticleSystem deathParticleSystem;
private void OnTriggerEnter2D(Collider2D collision)
{
#rest of the code
deathParticleSystem.time = 0;
deathParticleSystem.Play();
}
public void RespawnPlayer()
{
//rest of the code
deathParticleSystem.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
}

或者,您可以enabledisable与粒子预制件关联的gameObject

public GameObject deathParticlePrefab;
private void OnTriggerEnter2D(Collider2D collision)
{
#rest of the code
deathParticlePrefab.SetActive(true);
}
public void RespawnPlayer()
{
//rest of the code
deathParticlePrefab.SetActive(false);
}

您始终可以创建一个新脚本并将其分配给预制件,该预制件会在一定时间后销毁它:

using UnityEngine;
using System.Collections;
public class destroyOverTime : MonoBehaviour {
public float lifeTime;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
lifeTime -= Time.deltaTime;
if(lifeTime <= 0f)
{
Destroy(gameObject);
}
}
}

所以在这种情况下,你会把它分配给你的死亡粒子。如果要实例化对象,以便不会加载不必要的对象,则此脚本在多种方案中都很有用。

最新更新