如何在另一个函数中访问OnTriggerEnter2D中的值?

时间:2017-11-03 10:58:26

标签: c# unity3d destroy gameobject ienumerator

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中它也没有用。有点新手

1 个答案:

答案 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);
}