using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RedHP : MonoBehaviour
{
public float HP = 5;
public GameObject BlueWon;
public GameObject Restart;
void OnTriggerEnter2D(Collider2D trig)
{
if (trig.gameObject.tag == "ThrowableBlue")
{
StartCoroutine(BowlDestroyTime());
HP--;
if (HP <= 0)
{
BlueWon.SetActive(true);
Restart.SetActive(true);
PlayerBlueController.canMove = false;
PlayerBlueController.canFire = false;
}
}
}
IEnumerator BowlDestroyTime()
{
yield return new WaitForSeconds(1);
Destroy(trig.gameObject);
}
}
我只是想在太短的时间后摧毁我的物体,使它看起来更好。在IEnumerator
我无法访问trig.gameObject
,因为它是在OnTriggerEnter2D
中定义的。有没有办法获取这个值?
我也尝试将IEnumerator
放在OnTriggerEnter2D中它也没有用。有点新手
答案 0 :(得分:4)
你不必这样做。 Destroy
函数可以将第二个参数作为销毁对象之前的延迟时间。
Destroy(trig.gameObject, 1f);
如果您仍想使用协同程序执行此操作,只需使BowlDestroyTime
函数将GameObject
作为参数,然后将GameObject从OnTriggerEnter2D
函数传递给BowlDestroyTime
要破坏的功能。
void OnTriggerEnter2D(Collider2D trig)
{
if (trig.gameObject.tag == "ThrowableBlue")
{
StartCoroutine(BowlDestroyTime(trig.gameObject));
HP--;
if (HP <= 0)
{
BlueWon.SetActive(true);
Restart.SetActive(true);
PlayerBlueController.canMove = false;
PlayerBlueController.canFire = false;
}
}
}
IEnumerator BowlDestroyTime(GameObject tartgetObj)
{
yield return new WaitForSeconds(1);
Destroy(tartgetObj);
}