首页 > 解决方案 > 如何检查对象的任何子对象是否处于活动状态?

问题描述

我在我的游戏中创建了武器,我让武器在被拿走时不被激活,但现在玩家可以同时拿 2 把枪。我已将所有武器添加到一个空对象中,并且我想检查对象的任何子对象是否处于活动状态。所有武器都有相同的脚本,但布尔值不同。方法是这样的

void OnMouseDown()
    {
            if(weapon_is_taken == false)
            {
                weapon_is_taken = true;
            }
     }

标签: c#unity3d

解决方案


有多种方法取决于您的需要。

要回答您的标题,您可以例如使用

public bool IsAnyChildActive()
{
    // Iterates through all direct childs of this object
    foreach(Transform child in transform)
    {
        if(child.gameObject.activeSelf) return true;
    }

    return false;
}

但是,根据孩子的数量,这可能每次都会有点开销。


我假设您的目标是能够关闭激活的武器并立即将所有其他武器设置为非激活状态。

为此,您可以简单地将当前活动引用存储在您的 Weapon 类中,例如

public class Weapon : MonoBehaviour
{
    // Stores the reference to the currently active weapon
    private static Weapon currentlyActiveWeapon;

    // Read-only access from the outside
    // Only this class can change the value
    public static Weapon CurrentlyActiveWeapon
    {
        get => currentlyActiveWeapon;

        private set
        {
            if(currentlyActiveWeapon == value)
            {
                // Already the same reference -> nothing to do
                return;
            }

            // Is there a current weapon at all?
            if(currentlyActiveWeapon)
            {
                // Set the current weapon inactive
                currentlyActiveWeapon.gameObject.SetActive(false);
            }

            // Store the assigned value as the new active weapon
            currentlyActiveWeapon = value;
            // And set it active
            currentlyActiveWeapon.gameObject.SetActive(true);
        }
    }

    // Check if this is the currently active weapon
    public bool weapon_is_taken => currentlyActiveWeapon == this;

    public void SetThisWeaponActive()
    {
        CurrentlyActiveWeapon = this;
    }
}

推荐阅读