如何在另一个函数中访问 OnTriggerEnter2D 的值?
How to access a value from OnTriggerEnter2D in another function?
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
函数可以带第二个参数作为Object被销毁前的延迟时间。
Destroy(trig.gameObject, 1f);
如果您仍想使用协程来执行此操作,只需让 BowlDestroyTime
函数将 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);
}
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
函数可以带第二个参数作为Object被销毁前的延迟时间。
Destroy(trig.gameObject, 1f);
如果您仍想使用协程来执行此操作,只需让 BowlDestroyTime
函数将 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);
}