有没有一种方法可以检查GameObject是否已被破坏?

时间:2019-11-03 13:59:41

标签: c# unity3d game-development

我正在创建一个游戏,我想在玩家死后显示一个面板

我尝试了不同的方法,但是似乎没有一种方法可以做

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DeadOrAlive : MonoBehaviour
{

    public GameObject Player;
    public GameObject deadPanel;

    void Update()
    {
        if (!GameObject.FindWithTag("Player"))
        {
            deadPanel.SetActive(true);
        }
    }


}

2 个答案:

答案 0 :(得分:3)

要检查对象是否已销毁,应使用MonoBehavior的OnDestroy,如下所示:

// Attach this script to the player object
public class DeadOrAlive : MonoBehaviour
{
    public GameObject deadPanel;

    void OnDestroy()
    {
        deadPanel.SetActive(true);
    }
}

您也可以不破坏播放器对象,而是将其设置为活动/非活动状态,但是要以这种方式检查播放器是否已死亡或存活,则需要一个单独的对象来检查活动状态:

//Attach this to a object which isn't a child of the player, maybe a dummy object called "PlayerMonitor" which is always active
public class DeadOrAlive : MonoBehaviour
{
    public GameObject deadPanel;

    void Update()
    {
        if (!GameObject.FindWithTag("Player"))
        {
            deadPanel.SetActive(true);
        }
    }
}

好一阵子没有使用团结,却忘记了团结会变得多么奇怪。

答案 1 :(得分:0)

感谢@VincentBree这就是我的做法

  void Update()
{
    if (!Player.activeSelf)
    {
        deadPanel.SetActive(true);
    }
}