有没有办法检查游戏对象是否已被销毁? [英] Is there a way to check if a GameObject has been destroyed?

查看:39
本文介绍了有没有办法检查游戏对象是否已被销毁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a game and i want to show a panel when the player is dead

我尝试了不同的方法,但似乎没有一个能做我想做的

I've tried different approaches but none seems to do what I want

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


}

推荐答案

要检查对象是否已被销毁,您应该像这样使用 MonoBehavior 的 OnDestroy:

To check if a object has been destroyed, you should use MonoBehavior's OnDestroy like so:

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

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

您也可以不销毁玩家对象,而是将其设置为活动/非活动状态,但是要以这种方式检查玩家是死是活,您需要一个单独的对象来检查活动状态:

You can also instead of destroying the player object, set it to active/inactive, but to check if the player is dead or alive this way, you will need a separate object which checks the active state:

//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);
        }
    }
}

好久没用 unity 了,忘了它会有多奇怪.

Haven't used unity in a while and forgot how weird it could get.

这篇关于有没有办法检查游戏对象是否已被销毁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆