其他分享
首页 > 其他分享> > CodeGo.net>在另一个函数中如何从OnTriggerEnter2D访问值?

CodeGo.net>在另一个函数中如何从OnTriggerEnter2D访问值?

作者:互联网

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中,但它也没有用.金达新手

解决方法:

您不必这样做. 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);
}

标签:gameobject,destroy,ienumerator,unity3d,c
来源: https://codeday.me/bug/20191025/1929693.html