我尝试删除一个游戏对象(通电)但是即使在我删除它之后,粒子也会自我克隆。我怎么能解决这个问题?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerUp : MonoBehaviour {
public float multiplier = 1.4f;
public float duration = 4f;
public GameObject pickupEffect;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
StartCoroutine (Pickup(collision));
}
}
IEnumerator Pickup(Collider2D player)
{
Debug.Log("Power up picked up!");
Instantiate(pickupEffect, transform.position, transform.rotation;
PlayerStats stats = player.GetComponent<PlayerStats>();
stats.health *= multiplier;
GetComponent<SpriteRenderer>().enabled = false;
GetComponent<Collider2D>().enabled = false;
yield return new WaitForSeconds(duration);
stats.health /= multiplier;
Destroy(this);
}
}
答案 0 :(得分:2)
在你的协程结束时,将Destroy(this);
更改为Destroy(gameObject);
Destroy(this);
销毁PowerUp
组件。而Destroy(gameObject);
会摧毁整棵树。
同样可以连续多次调用OnTriggerEnter2D
,导致无限的实例化。您可以在StartCoroutine
之前添加约束以防止这种情况发生。
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
if (!flag)
StartCoroutine (Pickup(collision));
}
}
IEnumerator Pickup(Collider2D player)
{
flag = true;